file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
list | attention_mask
list | labels
list |
---|---|---|---|---|---|---|
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
/*
* @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() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() external virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) external virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () {
_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());
}
}
/**
* @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}.
*
* 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 Zuki is Context, IERC20, IERC20Metadata, Ownable, Pausable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
mapping (address => bool) private pausedAddress;
string private constant _name = "Zuki";
string private constant _symbol = "ZUKI";
uint8 private constant _decimals = 18;
uint256 private _totalSupply;
uint256 private _initialSupply = 7800000000000 * 10**18;
event ExternalTokenTransfered(address externalAddress,address toAddress, uint amount);
event EthFromContractTransferred(uint amount);
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor() {
_mint(_msgSender(), _initialSupply);
}
/**
* @dev Returns the name of the token.
*/
function name() external view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view virtual override 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 this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() external view virtual override returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() external view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) external view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) external virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) external 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) external 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
) external virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) external virtual onlyOwner returns (bool) {
_burn(_msgSender(), amount);
return true;
}
/**
* @dev Pause `contract` - pause events.
*
* See {ERC20Pausable-_pause}.
*/
function pauseContract() external virtual onlyOwner {
_pause();
}
/**
* @dev Pause `contract` - pause events.
*
* See {ERC20Pausable-_pause}.
*/
function unPauseContract() external virtual onlyOwner {
_unpause();
}
/**
* @dev Pause `contract` - pause events.
*
* See {ERC20Pausable-_pause}.
*/
function pauseAddress(address account) external virtual onlyOwner {
pausedAddress[account] = true;
}
/**
* @dev Pause `contract` - pause events.
*
* See {ERC20Pausable-_pause}.
*/
function unPauseAddress(address account) external virtual onlyOwner {
pausedAddress[account] = false;
}
/**
* @dev Returns true if the address is paused, and false otherwise.
*/
function isAddressPaused(address account) external view virtual returns (bool) {
return pausedAddress[account];
}
function withdrawToken(address _tokenContract, uint256 _amount) external onlyOwner {
require(_tokenContract != address(0), "Address cant be zero address");
IERC20 tokenContract = IERC20(_tokenContract);
tokenContract.transfer(msg.sender, _amount);
emit ExternalTokenTransfered(_tokenContract,msg.sender, _amount);
}
function getBalance() public view returns (uint256) {
return address(this).balance;
}
function withdrawEthFromContract(uint256 amount) external onlyOwner {
require(amount <= getBalance());
address payable _owner = payable(owner());
_owner.transfer(amount);
emit EthFromContractTransferred(amount);
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {
require(amount > 0, "BEP20: amount must be greater than 0");
require(!paused(), "ERC20Pausable: token transfer while contract paused");
require(!pausedAddress[from], "ERC20Pausable: token transfer while from-address paused");
require(!pausedAddress[to], "ERC20Pausable: token transfer while to-address paused");
}
} | * @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 {
require(amount > 0, "BEP20: amount must be greater than 0");
require(!paused(), "ERC20Pausable: token transfer while contract paused");
require(!pausedAddress[from], "ERC20Pausable: token transfer while from-address paused");
require(!pausedAddress[to], "ERC20Pausable: token transfer while to-address paused");
}
| 14,373,473 | [
1,
5394,
716,
353,
2566,
1865,
1281,
7412,
434,
2430,
18,
1220,
6104,
312,
474,
310,
471,
18305,
310,
18,
21020,
4636,
30,
300,
1347,
1375,
2080,
68,
471,
1375,
869,
68,
854,
3937,
1661,
17,
7124,
16,
1375,
8949,
68,
434,
12176,
2080,
10335,
11,
87,
2430,
903,
506,
358,
906,
4193,
358,
1375,
869,
8338,
300,
1347,
1375,
2080,
68,
353,
3634,
16,
1375,
8949,
68,
2430,
903,
506,
312,
474,
329,
364,
1375,
869,
8338,
300,
1347,
1375,
869,
68,
353,
3634,
16,
1375,
8949,
68,
434,
12176,
2080,
10335,
11,
87,
2430,
903,
506,
18305,
329,
18,
300,
1375,
2080,
68,
471,
1375,
869,
68,
854,
5903,
3937,
3634,
18,
2974,
16094,
1898,
2973,
9153,
16,
910,
358,
15187,
30,
9185,
30,
408,
2846,
17,
16351,
87,
18,
4539,
9940,
17,
10468,
63,
7736,
13725,
87,
8009,
19,
2,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
5771,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
2713,
5024,
288,
203,
3639,
2583,
12,
8949,
405,
374,
16,
315,
5948,
52,
3462,
30,
3844,
1297,
506,
6802,
2353,
374,
8863,
203,
3639,
2583,
12,
5,
8774,
3668,
9334,
315,
654,
39,
3462,
16507,
16665,
30,
1147,
7412,
1323,
6835,
17781,
8863,
203,
3639,
2583,
12,
5,
8774,
3668,
1887,
63,
2080,
6487,
315,
654,
39,
3462,
16507,
16665,
30,
1147,
7412,
1323,
628,
17,
2867,
17781,
8863,
203,
3639,
2583,
12,
5,
8774,
3668,
1887,
63,
869,
6487,
315,
654,
39,
3462,
16507,
16665,
30,
1147,
7412,
1323,
358,
17,
2867,
17781,
8863,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.7.6;
import "contracts/protocol/futures/StreamFuture.sol";
/**
* @title Contract for Aave Future
* @notice Handles the future mechanisms for the Aave platform
* @dev Implement directly the stream future abstraction as it fits the aToken IBT
*/
contract AaveFuture is StreamFuture {
}
pragma solidity 0.7.6;
import "contracts/protocol/futures/Future.sol";
/**
* @title Main future abstraction contract for the stream futures
* @notice Handles the stream future mecanisms
* @dev Basis of all mecanisms for futures (registrations, period switch)
*/
abstract contract StreamFuture is Future {
using SafeMathUpgradeable for uint256;
uint256[] internal scaledTotals;
/**
* @notice Intializer
* @param _controller the address of the controller
* @param _ibt the address of the corresponding IBT
* @param _periodDuration the length of the period (in days)
* @param _platformName the name of the platform and tools
* @param _deployerAddress the future deployer address
* @param _admin the address of the ACR admin
*/
function initialize(
address _controller,
address _ibt,
uint256 _periodDuration,
string memory _platformName,
address _deployerAddress,
address _admin
) public virtual override initializer {
super.initialize(_controller, _ibt, _periodDuration, _platformName, _deployerAddress, _admin);
scaledTotals.push();
scaledTotals.push();
}
/**
* @notice Sender registers an amount of IBT for the next period
* @param _user address to register to the future
* @param _amount amount of IBT to be registered
* @dev called by the controller only
*/
function register(address _user, uint256 _amount) public virtual override periodsActive nonReentrant depositsEnabled {
require(_amount > 0, "invalid amount to register");
IRegistry registry = IRegistry(controller.getRegistryAddress());
uint256 scaledInput =
IAPWineMaths(registry.getMathsUtils()).getScaledInput(
_amount,
scaledTotals[getNextPeriodIndex()],
ibt.balanceOf(address(this))
);
super.register(_user, scaledInput);
scaledTotals[getNextPeriodIndex()] = scaledTotals[getNextPeriodIndex()].add(scaledInput);
}
/**
* @notice Sender unregisters an amount of IBT for the next period
* @param _user user addresss
* @param _amount amount of IBT to be unregistered
* @dev 0 unregisters all
*/
function unregister(address _user, uint256 _amount) public virtual override nonReentrant withdrawalsEnabled {
require(hasRole(CONTROLLER_ROLE, msg.sender), "Caller is not allowed to unregister");
uint256 nextIndex = getNextPeriodIndex();
require(registrations[_user].startIndex == nextIndex, "There is no ongoing registration for the next period");
uint256 userScaledBalance = registrations[_user].scaledBalance;
IRegistry registry = IRegistry(controller.getRegistryAddress());
uint256 currentRegistered =
IAPWineMaths(registry.getMathsUtils()).getActualOutput(
userScaledBalance,
scaledTotals[nextIndex],
ibt.balanceOf(address(this))
);
uint256 scaledToUnregister;
uint256 toRefund;
if (_amount == 0) {
scaledToUnregister = userScaledBalance;
delete registrations[_user];
toRefund = currentRegistered;
} else {
require(currentRegistered >= _amount, "Invalid amount to unregister");
scaledToUnregister = (registrations[_user].scaledBalance.mul(_amount)).div(currentRegistered);
registrations[_user].scaledBalance = registrations[_user].scaledBalance.sub(scaledToUnregister);
toRefund = _amount;
}
scaledTotals[nextIndex] = scaledTotals[nextIndex].sub(scaledToUnregister);
ibt.transfer(_user, toRefund);
}
/**
* @notice Start a new period
* @dev needs corresponding permissions for sender
*/
function startNewPeriod() public virtual override nextPeriodAvailable periodsActive nonReentrant {
require(hasRole(CONTROLLER_ROLE, msg.sender), "Caller is not allowed to start the next period");
uint256 nextPeriodID = getNextPeriodIndex();
registrationsTotals[nextPeriodID] = ibt.balanceOf(address(this));
/* Yield */
uint256 yield = ibt.balanceOf(address(futureVault)).sub(apwibt.totalSupply());
futureWallet.registerExpiredFuture(yield); // Yield deposit in the futureWallet contract
if (yield > 0) assert(ibt.transferFrom(address(futureVault), address(futureWallet), yield));
/* Period Switch*/
if (registrationsTotals[nextPeriodID] > 0) {
apwibt.mint(address(this), registrationsTotals[nextPeriodID]); // Mint new apwIBTs
ibt.transfer(address(futureVault), registrationsTotals[nextPeriodID]); // Send IBT to future for the new period
}
registrationsTotals.push();
scaledTotals.push();
/* Future Yield Token */
address fytAddress = deployFutureYieldToken(nextPeriodID);
emit NewPeriodStarted(nextPeriodID, fytAddress);
}
/**
* @notice Getter for user registered amount
* @param _user user to return the registered funds of
* @return the registered amount, 0 if no registrations
* @dev the registration can be older than the next period
*/
function getRegisteredAmount(address _user) public view virtual override returns (uint256) {
uint256 periodID = registrations[_user].startIndex;
IRegistry registry = IRegistry(controller.getRegistryAddress());
if (periodID == getNextPeriodIndex()) {
return
IAPWineMaths(registry.getMathsUtils()).getActualOutput(
registrations[_user].scaledBalance,
scaledTotals[periodID],
ibt.balanceOf(address(this))
);
} else {
return 0;
}
}
/**
* @notice Getter for the amount of apwIBT that the user can claim
* @param _user user to check the check the claimable apwIBT of
* @return the amount of apwIBT claimable by the user
*/
function getClaimableAPWIBT(address _user) public view override returns (uint256) {
if (!hasClaimableAPWIBT(_user)) return 0;
IRegistry registry = IRegistry(controller.getRegistryAddress());
return
IAPWineMaths(registry.getMathsUtils()).getActualOutput(
registrations[_user].scaledBalance,
scaledTotals[registrations[_user].startIndex],
registrationsTotals[registrations[_user].startIndex]
);
}
/**
* @notice Getter for yield that is generated by the user funds during the current period
* @param _user user to check the unrealised yield of
* @return the yield (amount of IBT) currently generated by the locked funds of the user
*/
function getUnrealisedYield(address _user) public view override returns (uint256) {
return
(
(ibt.balanceOf(address(futureVault)).sub(apwibt.totalSupply())).mul(
fyts[getNextPeriodIndex() - 1].balanceOf(_user)
)
)
.div(fyts[getNextPeriodIndex() - 1].totalSupply());
}
}
pragma solidity 0.7.6;
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "contracts/interfaces/IProxyFactory.sol";
import "contracts/interfaces/apwine/tokens/IFutureYieldToken.sol";
import "contracts/interfaces/apwine/utils/IAPWineMath.sol";
import "contracts/interfaces/apwine/tokens/IAPWineIBT.sol";
import "contracts/interfaces/apwine/IFutureWallet.sol";
import "contracts/interfaces/apwine/IController.sol";
import "contracts/interfaces/apwine/IFutureVault.sol";
import "contracts/interfaces/apwine/ILiquidityGauge.sol";
import "contracts/interfaces/apwine/IRegistry.sol";
/**
* @title Main future abstraction contract
* @notice Handles the future mechanisms
* @dev Basis of all mecanisms for futures (registrations, period switch)
*/
abstract contract Future is Initializable, AccessControlUpgradeable, ReentrancyGuardUpgradeable {
using SafeMathUpgradeable for uint256;
/* Structs */
struct Registration {
uint256 startIndex;
uint256 scaledBalance;
}
uint256[] internal registrationsTotals;
/* ACR */
bytes32 public constant CONTROLLER_ROLE = keccak256("CONTROLLER_ROLE");
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
bytes32 public constant FUTURE_DEPLOYER = keccak256("FUTURE_DEPLOYER");
/* State variables */
mapping(address => uint256) internal lastPeriodClaimed;
mapping(address => Registration) internal registrations;
IFutureYieldToken[] public fyts;
/* External contracts */
IFutureVault internal futureVault;
IFutureWallet internal futureWallet;
ILiquidityGauge internal liquidityGauge;
ERC20 internal ibt;
IAPWineIBT internal apwibt;
IController internal controller;
/* Settings */
uint256 public PERIOD_DURATION;
string public PLATFORM_NAME;
bool public PAUSED;
bool public WITHRAWALS_PAUSED;
bool public DEPOSITS_PAUSED;
/* Events */
event UserRegistered(address _userAddress, uint256 _amount, uint256 _periodIndex);
event NewPeriodStarted(uint256 _newPeriodIndex, address _fytAddress);
event FutureVaultSet(address _futureVault);
event FutureWalletSet(address _futureWallet);
event LiquidityGaugeSet(address _liquidityGauge);
event FundsWithdrawn(address _user, uint256 _amount);
event PeriodsPaused();
event PeriodsResumed();
event DepositsPaused();
event DepositsResumed();
event WithdrawalsPaused();
event WithdrawalsResumed();
event APWIBTSet(address _apwibt);
event LiquidityTransfersPaused();
event LiquidityTransfersResumed();
/* Modifiers */
modifier nextPeriodAvailable() {
uint256 controllerDelay = controller.STARTING_DELAY();
require(
controller.getNextPeriodStart(PERIOD_DURATION) < block.timestamp.add(controllerDelay),
"Next period start range not reached yet"
);
_;
}
modifier periodsActive() {
require(!PAUSED, "New periods are currently paused");
_;
}
modifier withdrawalsEnabled() {
require(!WITHRAWALS_PAUSED, "withdrawals are disabled");
_;
}
modifier depositsEnabled() {
require(!DEPOSITS_PAUSED, "desposits are disabled");
_;
}
/* Initializer */
/**
* @notice Intializer
* @param _controller the address of the controller
* @param _ibt the address of the corresponding IBT
* @param _periodDuration the length of the period (in days)
* @param _platformName the name of the platform and tools
* @param _admin the address of the ACR admin
*/
function initialize(
address _controller,
address _ibt,
uint256 _periodDuration,
string memory _platformName,
address _deployerAddress,
address _admin
) public virtual initializer {
controller = IController(_controller);
ibt = ERC20(_ibt);
PERIOD_DURATION = _periodDuration * (1 days);
PLATFORM_NAME = _platformName;
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
_setupRole(ADMIN_ROLE, _admin);
_setupRole(CONTROLLER_ROLE, _controller);
_setupRole(FUTURE_DEPLOYER, _deployerAddress);
registrationsTotals.push();
registrationsTotals.push();
fyts.push();
IRegistry registry = IRegistry(controller.getRegistryAddress());
string memory ibtSymbol = controller.getFutureIBTSymbol(ibt.symbol(), _platformName, PERIOD_DURATION);
bytes memory payload =
abi.encodeWithSignature(
"initialize(string,string,uint8,address)",
ibtSymbol,
ibtSymbol,
ibt.decimals(),
address(this)
);
apwibt = IAPWineIBT(
IProxyFactory(registry.getProxyFactoryAddress()).deployMinimal(registry.getAPWineIBTLogicAddress(), payload)
);
emit APWIBTSet(address(apwibt));
}
/* Period functions */
/**
* @notice Start a new period
* @dev needs corresponding permissions for sender
*/
function startNewPeriod() public virtual;
/**
* @notice Sender registers an amount of IBT for the next period
* @param _user address to register to the future
* @param _amount amount of IBT to be registered
* @dev called by the controller only
*/
function register(address _user, uint256 _amount) public virtual periodsActive depositsEnabled periodsActive {
require(hasRole(CONTROLLER_ROLE, msg.sender), "Caller is not allowed to register");
uint256 nextIndex = getNextPeriodIndex();
if (registrations[_user].scaledBalance == 0) {
// User has no record
_register(_user, _amount);
} else {
if (registrations[_user].startIndex == nextIndex) {
// User has already an existing registration for the next period
registrations[_user].scaledBalance = registrations[_user].scaledBalance.add(_amount);
} else {
// User had an unclaimed registation from a previous period
_claimAPWIBT(_user);
_register(_user, _amount);
}
}
emit UserRegistered(_user, _amount, nextIndex);
}
function _register(address _user, uint256 _initialScaledBalance) internal virtual {
registrations[_user] = Registration({startIndex: getNextPeriodIndex(), scaledBalance: _initialScaledBalance});
}
/**
* @notice Sender unregisters an amount of IBT for the next period
* @param _user user address
* @param _amount amount of IBT to be unregistered
*/
function unregister(address _user, uint256 _amount) public virtual;
/* Claim functions */
/**
* @notice Send the user their owed FYT (and apwIBT if there are some claimable)
* @param _user address of the user to send the FYT to
*/
function claimFYT(address _user) public virtual nonReentrant {
require(hasClaimableFYT(_user), "No FYT claimable for this address");
if (hasClaimableAPWIBT(_user)) _claimAPWIBT(_user);
else _claimFYT(_user);
}
function _claimFYT(address _user) internal virtual {
uint256 nextIndex = getNextPeriodIndex();
for (uint256 i = lastPeriodClaimed[_user] + 1; i < nextIndex; i++) {
claimFYTforPeriod(_user, i);
}
}
function claimFYTforPeriod(address _user, uint256 _periodIndex) internal virtual {
assert((lastPeriodClaimed[_user] + 1) == _periodIndex);
assert(_periodIndex < getNextPeriodIndex());
assert(_periodIndex != 0);
lastPeriodClaimed[_user] = _periodIndex;
fyts[_periodIndex].transfer(_user, apwibt.balanceOf(_user));
}
function _claimAPWIBT(address _user) internal virtual {
uint256 nextIndex = getNextPeriodIndex();
uint256 claimableAPWIBT = getClaimableAPWIBT(_user);
if (_hasOnlyClaimableFYT(_user)) _claimFYT(_user);
apwibt.transfer(_user, claimableAPWIBT);
for (uint256 i = registrations[_user].startIndex; i < nextIndex; i++) {
// get unclaimed fyt
fyts[i].transfer(_user, claimableAPWIBT);
}
lastPeriodClaimed[_user] = nextIndex - 1;
delete registrations[_user];
}
/**
* @notice Sender unlocks the locked funds corresponding to their apwIBT holding
* @param _user user adress
* @param _amount amount of funds to unlock
* @dev will require a transfer of FYT of the ongoing period corresponding to the funds unlocked
*/
function withdrawLockFunds(address _user, uint256 _amount) public virtual nonReentrant withdrawalsEnabled {
require(hasRole(CONTROLLER_ROLE, msg.sender), "Caller is not allowed to withdraw locked funds");
require((_amount > 0) && (_amount <= apwibt.balanceOf(_user)), "Invalid amount");
if (hasClaimableAPWIBT(_user)) {
_claimAPWIBT(_user);
} else if (hasClaimableFYT(_user)) {
_claimFYT(_user);
}
uint256 unlockableFunds = getUnlockableFunds(_user);
uint256 unrealisedYield = getUnrealisedYield(_user);
uint256 fundsToBeUnlocked = _amount.mul(unlockableFunds).div(apwibt.balanceOf(_user));
uint256 yieldToBeUnlocked = _amount.mul(unrealisedYield).div(apwibt.balanceOf(_user));
uint256 yieldToBeRedeemed;
if (PAUSED) {
yieldToBeRedeemed = yieldToBeUnlocked;
} else {
yieldToBeRedeemed = (yieldToBeUnlocked.mul(controller.getUnlockYieldFactor(PERIOD_DURATION))).div(1000);
}
ibt.transferFrom(address(futureVault), _user, fundsToBeUnlocked.add(yieldToBeRedeemed));
uint256 treasuryFee = unrealisedYield.sub(yieldToBeRedeemed);
if (treasuryFee > 0) {
ibt.transferFrom(
address(futureVault),
IRegistry(controller.getRegistryAddress()).getTreasuryAddress(),
treasuryFee
);
}
apwibt.burnFrom(_user, _amount);
fyts[getNextPeriodIndex() - 1].burnFrom(_user, _amount);
emit FundsWithdrawn(_user, _amount);
}
/* Utilitary functions */
function deployFutureYieldToken(uint256 _internalPeriodID) internal returns (address) {
IRegistry registry = IRegistry(controller.getRegistryAddress());
string memory tokenDenomination = controller.getFYTSymbol(apwibt.symbol(), PERIOD_DURATION);
bytes memory payload =
abi.encodeWithSignature(
"initialize(string,string,uint8,uint256,address)",
tokenDenomination,
tokenDenomination,
ibt.decimals(),
_internalPeriodID,
address(this)
);
IFutureYieldToken newToken =
IFutureYieldToken(
IProxyFactory(registry.getProxyFactoryAddress()).deployMinimal(registry.getFYTLogicAddress(), payload)
);
fyts.push(newToken);
newToken.mint(address(this), apwibt.totalSupply());
return address(newToken);
}
/* Getters */
/**
* @notice Check if a user has unclaimed FYT
* @param _user the user to check
* @return true if the user can claim some FYT, false otherwise
*/
function hasClaimableFYT(address _user) public view returns (bool) {
return hasClaimableAPWIBT(_user) || _hasOnlyClaimableFYT(_user);
}
function _hasOnlyClaimableFYT(address _user) internal view returns (bool) {
return lastPeriodClaimed[_user] != 0 && lastPeriodClaimed[_user] < getNextPeriodIndex() - 1;
}
/**
* @notice Check if a user has IBT not claimed
* @param _user the user to check
* @return true if the user can claim some IBT, false otherwise
*/
function hasClaimableAPWIBT(address _user) public view returns (bool) {
return (registrations[_user].startIndex < getNextPeriodIndex()) && (registrations[_user].scaledBalance > 0);
}
/**
* @notice Getter for next period index
* @return next period index
* @dev index starts at 1
*/
function getNextPeriodIndex() public view virtual returns (uint256) {
return registrationsTotals.length - 1;
}
/**
* @notice Getter for the amount of apwIBT that the user can claim
* @param _user user to check the check the claimable apwIBT of
* @return the amount of apwIBT claimable by the user
*/
function getClaimableAPWIBT(address _user) public view virtual returns (uint256);
/**
* @notice Getter for the amount of FYT that the user can claim for a certain period
* @param _user the user to check the claimable FYT of
* @param _periodID period ID to check the claimable FYT of
* @return the amount of FYT claimable by the user for this period ID
*/
function getClaimableFYTForPeriod(address _user, uint256 _periodID) public view virtual returns (uint256) {
if (
_periodID >= getNextPeriodIndex() ||
registrations[_user].startIndex == 0 ||
registrations[_user].scaledBalance == 0 ||
registrations[_user].startIndex > _periodID
) {
return 0;
} else {
return getClaimableAPWIBT(_user);
}
}
/**
* @notice Getter for user IBT amount that is unlockable
* @param _user the user to unlock the IBT from
* @return the amount of IBT the user can unlock
*/
function getUnlockableFunds(address _user) public view virtual returns (uint256) {
return apwibt.balanceOf(_user);
}
/**
* @notice Getter for user registered amount
* @param _user the user to return the registered funds of
* @return the registered amount, 0 if no registrations
* @dev the registration can be older than the next period
*/
function getRegisteredAmount(address _user) public view virtual returns (uint256);
/**
* @notice Getter for yield that is generated by the user funds during the current period
* @param _user the user to check the unrealized yield of
* @return the yield (amount of IBT) currently generated by the locked funds of the user
*/
function getUnrealisedYield(address _user) public view virtual returns (uint256);
/**
* @notice Getter for controller address
* @return the controller address
*/
function getControllerAddress() public view returns (address) {
return address(controller);
}
/**
* @notice Getter for future wallet address
* @return future wallet address
*/
function getFutureVaultAddress() public view returns (address) {
return address(futureVault);
}
/**
* @notice Getter for futureWallet address
* @return futureWallet address
*/
function getFutureWalletAddress() public view returns (address) {
return address(futureWallet);
}
/**
* @notice Getter for liquidity gauge address
* @return liquidity gauge address
*/
function getLiquidityGaugeAddress() public view returns (address) {
return address(liquidityGauge);
}
/**
* @notice Getter for the IBT address
* @return IBT address
*/
function getIBTAddress() public view returns (address) {
return address(ibt);
}
/**
* @notice Getter for future apwIBT address
* @return apwIBT address
*/
function getAPWIBTAddress() public view returns (address) {
return address(apwibt);
}
/**
* @notice Getter for FYT address of a particular period
* @param _periodIndex period index
* @return FYT address
*/
function getFYTofPeriod(uint256 _periodIndex) public view returns (address) {
require(_periodIndex < getNextPeriodIndex(), "No FYT for this period yet");
return address(fyts[_periodIndex]);
}
/* Admin function */
/**
* @notice Pause registrations and the creation of new periods
*/
function pausePeriods() public {
require(
(hasRole(ADMIN_ROLE, msg.sender) || hasRole(CONTROLLER_ROLE, msg.sender)),
"Caller is not allowed to pause future"
);
PAUSED = true;
emit PeriodsPaused();
}
/**
* @notice Resume registrations and the creation of new periods
*/
function resumePeriods() public {
require(
(hasRole(ADMIN_ROLE, msg.sender) || hasRole(CONTROLLER_ROLE, msg.sender)),
"Caller is not allowed to resume future"
);
PAUSED = false;
emit PeriodsResumed();
}
/**
* @notice Pause withdrawals
*/
function pauseWithdrawals() public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not allowed to pause withdrawals");
WITHRAWALS_PAUSED = true;
emit WithdrawalsPaused();
}
/**
* @notice Resume withdrawals
*/
function resumeWithdrawals() public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not allowed to resume withdrawals");
WITHRAWALS_PAUSED = false;
emit WithdrawalsResumed();
}
/**
* @notice Pause deposits
*/
function pauseDeposits() public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not allowed to pause deposits");
DEPOSITS_PAUSED = true;
emit DepositsPaused();
}
/**
* @notice Resume deposits
*/
function resumeDeposits() public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not allowed to resume deposits");
DEPOSITS_PAUSED = false;
emit DepositsResumed();
}
/**
* @notice Pause liquidity transfers
*/
function pauseLiquidityTransfers() public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not allowed to pause liquidity transfer");
apwibt.pause();
emit LiquidityTransfersPaused();
}
/**
* @notice Resume liquidity transfers
*/
function resumeLiquidityTransfers() public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not allowed to resume liquidity transfer");
apwibt.unpause();
emit LiquidityTransfersResumed();
}
/**
* @notice Set future wallet address
* @param _futureVault the address of the new future wallet
* @dev needs corresponding permissions for sender
*/
function setFutureVault(address _futureVault) public {
require(hasRole(FUTURE_DEPLOYER, msg.sender), "Caller is not allowed to set the future vault address");
futureVault = IFutureVault(_futureVault);
emit FutureVaultSet(_futureVault);
}
/**
* @notice Set futureWallet address
* @param _futureWallet the address of the new futureWallet
* @dev needs corresponding permissions for sender
*/
function setFutureWallet(address _futureWallet) public {
require(hasRole(FUTURE_DEPLOYER, msg.sender), "Caller is not allowed to set the future wallet address");
futureWallet = IFutureWallet(_futureWallet);
emit FutureWalletSet(_futureWallet);
}
/**
* @notice Set liquidity gauge address
* @param _liquidityGauge the address of the new liquidity gauge
* @dev needs corresponding permissions for sender
*/
function setLiquidityGauge(address _liquidityGauge) public {
require(hasRole(FUTURE_DEPLOYER, msg.sender), "Caller is not allowed to set the liquidity gauge address");
liquidityGauge = ILiquidityGauge(_liquidityGauge);
emit LiquidityGaugeSet(_liquidityGauge);
}
/**
* @notice Set apwibt address
* @param _apwibt the address of the new apwibt
* @dev used only for exceptional purpose
*/
function setAPWIBT(address _apwibt) public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not allowed to set the apwibt");
apwibt = IAPWineIBT(_apwibt);
emit APWIBTSet(_apwibt);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSetUpgradeable.sol";
import "../utils/AddressUpgradeable.sol";
import "../GSN/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using AddressUpgradeable for address;
struct RoleData {
EnumerableSetUpgradeable.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _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 {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-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 || _isConstructor() || !_initialized, "Initializable: contract is already 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;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// 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;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_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;
}
uint256[49] private __gap;
}
pragma solidity 0.7.6;
interface IProxyFactory {
function deployMinimal(address _logic, bytes memory _data) external returns (address proxy);
}
pragma solidity 0.7.6;
import "contracts/interfaces/ERC20.sol";
interface IFutureYieldToken is ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) external;
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) external;
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) external;
}
pragma solidity 0.7.6;
interface IAPWineMaths {
/**
* @notice scale an input
* @param _actualValue the original value of the input
* @param _initialSum the scaled value of the sum of the inputs
* @param _actualSum the current value of the sum of the inputs
*/
function getScaledInput(
uint256 _actualValue,
uint256 _initialSum,
uint256 _actualSum
) external pure returns (uint256);
/**
* @notice scale back a value to the output
* @param _scaledOutput the current scaled output
* @param _initialSum the scaled value of the sum of the inputs
* @param _actualSum the current value of the sum of the inputs
*/
function getActualOutput(
uint256 _scaledOutput,
uint256 _initialSum,
uint256 _actualSum
) external pure returns (uint256);
}
pragma solidity 0.7.6;
import "contracts/interfaces/ERC20.sol";
interface IAPWineIBT is ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) external;
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) external;
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) external;
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() external;
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() external;
}
pragma solidity 0.7.6;
interface IFutureWallet {
/**
* @notice Intializer
* @param _futureAddress the address of the corresponding future
* @param _adminAddress the address of the ACR admin
*/
function initialize(address _futureAddress, address _adminAddress) external;
/**
* @notice register the yield of an expired period
* @param _amount the amount of yield to be registered
*/
function registerExpiredFuture(uint256 _amount) external;
/**
* @notice redeem the yield of the underlying yield of the FYT held by the sender
* @param _periodIndex the index of the period to redeem the yield from
*/
function redeemYield(uint256 _periodIndex) external;
/**
* @notice return the yield that could be redeemed by an address for a particular period
* @param _periodIndex the index of the corresponding period
* @param _tokenHolder the FYT holder
* @return the yield that could be redeemed by the token holder for this period
*/
function getRedeemableYield(uint256 _periodIndex, address _tokenHolder) external view returns (uint256);
/**
* @notice getter for the address of the future corresponding to this future wallet
* @return the address of the future
*/
function getFutureAddress() external view returns (address);
/**
* @notice getter for the address of the IBT corresponding to this future wallet
* @return the address of the IBT
*/
function getIBTAddress() external view returns (address);
}
pragma solidity 0.7.6;
interface IController {
/* Getters */
function STARTING_DELAY() external view returns (uint256);
/* Initializer */
/**
* @notice Initializer of the Controller contract
* @param _admin the address of the admin
*/
function initialize(address _admin) external;
/* Future Settings Setters */
/**
* @notice Change the delay for starting a new period
* @param _startingDelay the new delay (+-) to start the next period
*/
function setPeriodStartingDelay(uint256 _startingDelay) external;
/**
* @notice Set the next period switch timestamp for the future with corresponding duration
* @param _periodDuration the duration of a period
* @param _nextPeriodTimestamp the next period switch timestamp
*/
function setNextPeriodSwitchTimestamp(uint256 _periodDuration, uint256 _nextPeriodTimestamp) external;
/**
* @notice Set a new factor for the portion of the yield that is claimable when withdrawing funds during an ongoing period
* @param _periodDuration the duration of the periods
* @param _claimableYieldFactor the portion of the yield that is claimable
*/
function setUnlockClaimableFactor(uint256 _periodDuration, uint256 _claimableYieldFactor) external;
/* User Methods */
/**
* @notice Register an amount of IBT from the sender to the corresponding future
* @param _future the address of the future to be registered to
* @param _amount the amount to register
*/
function register(address _future, uint256 _amount) external;
/**
* @notice Unregister an amount of IBT from the sender to the corresponding future
* @param _future the address of the future to be unregistered from
* @param _amount the amount to unregister
*/
function unregister(address _future, uint256 _amount) external;
/**
* @notice Withdraw deposited funds from APWine
* @param _future the address of the future to withdraw the IBT from
* @param _amount the amount to withdraw
*/
function withdrawLockFunds(address _future, uint256 _amount) external;
/**
* @notice Claim FYT of the msg.sender
* @param _future the future from which to claim the FYT
*/
function claimFYT(address _future) external;
/**
* @notice Get the list of futures from which a user can claim FYT
* @param _user the user to check
*/
function getFuturesWithClaimableFYT(address _user) external view returns (address[] memory);
/**
* @notice Getter for the registry address of the protocol
* @return the address of the protocol registry
*/
function getRegistryAddress() external view returns (address);
/**
* @notice Getter for the symbol of the apwIBT of one future
* @param _ibtSymbol the IBT of the external protocol
* @param _platform the external protocol name
* @param _periodDuration the duration of the periods for the future
* @return the generated symbol of the apwIBT
*/
function getFutureIBTSymbol(
string memory _ibtSymbol,
string memory _platform,
uint256 _periodDuration
) external pure returns (string memory);
/**
* @notice Getter for the symbol of the FYT of one future
* @param _apwibtSymbol the apwIBT symbol for this future
* @param _periodDuration the duration of the periods for this future
* @return the generated symbol of the FYT
*/
function getFYTSymbol(string memory _apwibtSymbol, uint256 _periodDuration) external view returns (string memory);
/**
* @notice Getter for the period index depending on the period duration of the future
* @param _periodDuration the periods duration
* @return the period index
*/
function getPeriodIndex(uint256 _periodDuration) external view returns (uint256);
/**
* @notice Getter for beginning timestamp of the next period for the futures with a defined periods duration
* @param _periodDuration the periods duration
* @return the timestamp of the beginning of the next period
*/
function getNextPeriodStart(uint256 _periodDuration) external view returns (uint256);
/**
* @notice Getter for the factor of claimable yield when unlocking
* @param _periodDuration the periods duration
* @return the factor of claimable yield of the last period
*/
function getUnlockYieldFactor(uint256 _periodDuration) external view returns (uint256);
/**
* @notice Getter for the list of future durations registered in the contract
* @return the list of futures duration
*/
function getDurations() external view returns (uint256[] memory);
/**
* @notice Register a newly created future in the registry
* @param _newFuture the address of the new future
*/
function registerNewFuture(address _newFuture) external;
/**
* @notice Unregister a future from the registry
* @param _future the address of the future to unregister
*/
function unregisterFuture(address _future) external;
/**
* @notice Start all the futures that have a defined periods duration to synchronize them
* @param _periodDuration the periods duration of the futures to start
*/
function startFuturesByPeriodDuration(uint256 _periodDuration) external;
/**
* @notice Getter for the futures by periods duration
* @param _periodDuration the periods duration of the futures to return
*/
function getFuturesWithDuration(uint256 _periodDuration) external view returns (address[] memory);
/**
* @notice Register the sender to the corresponding future
* @param _user the address of the user
* @param _futureAddress the addresses of the futures to claim the fyts from
*/
function claimSelectedYield(address _user, address[] memory _futureAddress) external;
function getRoleMember(bytes32 role, uint256 index) external view returns (address); // OZ ACL getter
/**
* @notice Interrupt a future avoiding news registrations
* @param _future the address of the future to pause
* @dev should only be called in extraordinary situations by the admin of the contract
*/
function pauseFuture(address _future) external;
/**
* @notice Resume a future that has been paused
* @param _future the address of the future to resume
* @dev should only be called in extraordinary situations by the admin of the contract
*/
function resumeFuture(address _future) external;
}
pragma solidity 0.7.6;
interface IFutureVault {
/**
* @notice Intializer
* @param _futureAddress the address of the corresponding future
* @param _adminAddress the address of the corresponding admin
*/
function initialize(address _futureAddress, address _adminAddress) external;
/**
* @notice Getter for the future address
* @return the future address linked to this vault
*/
function getFutureAddress() external view returns (address);
/**
* @notice Approve another token to be transfered from this contract by the future
*/
function approveAdditionalToken(address _tokenAddress) external;
}
pragma solidity 0.7.6;
interface ILiquidityGauge {
/**
* @notice Contract Initializer
* @param _gaugeController the address of the gauge controller
* @param _future the address of the corresponding future
*/
function initialize(address _gaugeController, address _future) external;
/**
* @notice Register new liquidity added to the future
* @param _amount the liquidity amount added
* @dev must be called from the future contract
*/
function registerNewFutureLiquidity(uint256 _amount) external;
/**
* @notice Unregister liquidity withdrawn from to the future
* @param _amount the liquidity amount withdrawn
* @dev must be called from the future contract
*/
function unregisterFutureLiquidity(uint256 _amount) external;
/**
* @notice update gauge and user liquidity state then return the new redeemable
* @param _user the user to update and return the redeemable of
*/
function updateAndGetRedeemable(address _user) external returns (uint256);
/**
* @notice Log an update of the inflated volume
*/
function updateInflatedVolume() external;
/**
* @notice Getter for the last inflated amount
* @return the last inflated amount
*/
function getLastInflatedAmount() external view returns (uint256);
/**
* @notice Getter for redeemable APWs of one user
* @param _user the user to check the redeemable APW of
* @return the amount of redeemable APW
*/
function getUserRedeemable(address _user) external view returns (uint256);
/**
* @notice Register new user liquidity
* @param _user the user to register the liquidity of
*/
function registerUserLiquidity(address _user) external;
/**
* @notice Delete a user liquidity registration
* @param _user the user to delete the liquidity registration of
*/
function deleteUserLiquidityRegistration(address _user) external;
/**
* @notice Register new user liquidity
* @param _sender the user to transfer the liquidity from
* @param _receiver the user to transfer the liquidity to
* @param _amount the amount of liquidity to transfer
*/
function transferUserLiquidty(
address _sender,
address _receiver,
uint256 _amount
) external;
/**
* @notice Update the current stored liquidity of one user
* @param _user the user to update the liquidity of
*/
function updateUserLiquidity(address _user) external;
/**
* @notice Remove liquidity from on user address
* @param _user the user to remove the liquidity from
* @param _amount the amount of liquidity to remove
*/
function removeUserLiquidity(address _user, uint256 _amount) external;
}
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;
interface IRegistry {
/**
* @notice Initializer of the contract
* @param _admin the address of the admin of the contract
*/
function initialize(address _admin) external;
/* Setters */
/**
* @notice Setter for the treasury address
* @param _newTreasury the address of the new treasury
*/
function setTreasury(address _newTreasury) external;
/**
* @notice Setter for the gauge controller address
* @param _newGaugeController the address of the new gauge controller
*/
function setGaugeController(address _newGaugeController) external;
/**
* @notice Setter for the controller address
* @param _newController the address of the new controller
*/
function setController(address _newController) external;
/**
* @notice Setter for the APW token address
* @param _newAPW the address of the APW token
*/
function setAPW(address _newAPW) external;
/**
* @notice Setter for the proxy factory address
* @param _proxyFactory the address of the new proxy factory
*/
function setProxyFactory(address _proxyFactory) external;
/**
* @notice Setter for the liquidity gauge address
* @param _liquidityGaugeLogic the address of the new liquidity gauge logic
*/
function setLiquidityGaugeLogic(address _liquidityGaugeLogic) external;
/**
* @notice Setter for the APWine IBT logic address
* @param _APWineIBTLogic the address of the new APWine IBT logic
*/
function setAPWineIBTLogic(address _APWineIBTLogic) external;
/**
* @notice Setter for the APWine FYT logic address
* @param _FYTLogic the address of the new APWine FYT logic
*/
function setFYTLogic(address _FYTLogic) external;
/**
* @notice Setter for the maths utils address
* @param _mathsUtils the address of the new math utils
*/
function setMathsUtils(address _mathsUtils) external;
/**
* @notice Setter for the naming utils address
* @param _namingUtils the address of the new naming utils
*/
function setNamingUtils(address _namingUtils) external;
/**
* @notice Getter for the controller address
* @return the address of the controller
*/
function getControllerAddress() external view returns (address);
/**
* @notice Getter for the treasury address
* @return the address of the treasury
*/
function getTreasuryAddress() external view returns (address);
/**
* @notice Getter for the gauge controller address
* @return the address of the gauge controller
*/
function getGaugeControllerAddress() external view returns (address);
/**
* @notice Getter for the DAO address
* @return the address of the DAO that has admin rights on the APW token
*/
function getDAOAddress() external returns (address);
/**
* @notice Getter for the APW token address
* @return the address the APW token
*/
function getAPWAddress() external view returns (address);
/**
* @notice Getter for the vesting contract address
* @return the vesting contract address
*/
function getVestingAddress() external view returns (address);
/**
* @notice Getter for the proxy factory address
* @return the proxy factory address
*/
function getProxyFactoryAddress() external view returns (address);
/**
* @notice Getter for liquidity gauge logic address
* @return the liquidity gauge logic address
*/
function getLiquidityGaugeLogicAddress() external view returns (address);
/**
* @notice Getter for APWine IBT logic address
* @return the APWine IBT logic address
*/
function getAPWineIBTLogicAddress() external view returns (address);
/**
* @notice Getter for APWine FYT logic address
* @return the APWine FYT logic address
*/
function getFYTLogicAddress() external view returns (address);
/**
* @notice Getter for math utils address
* @return the math utils address
*/
function getMathsUtils() external view returns (address);
/**
* @notice Getter for naming utils address
* @return the naming utils address
*/
function getNamingUtils() external view returns (address);
/* Future factory */
/**
* @notice Register a new future factory in the registry
* @param _futureFactory the address of the future factory contract
* @param _futureFactoryName the name of the future factory
*/
function addFutureFactory(address _futureFactory, string memory _futureFactoryName) external;
/**
* @notice Getter to check if a future factory is registered
* @param _futureFactory the address of the future factory contract to check the registration of
* @return true if it is, false otherwise
*/
function isRegisteredFutureFactory(address _futureFactory) external view returns (bool);
/**
* @notice Getter for the future factory registered at an index
* @param _index the index of the future factory to return
* @return the address of the corresponding future factory
*/
function getFutureFactoryAt(uint256 _index) external view returns (address);
/**
* @notice Getter for number of future factories registered
* @return the number of future factory registered
*/
function futureFactoryCount() external view returns (uint256);
/**
* @notice Getter for name of a future factory contract
* @param _futureFactory the address of a future factory
* @return the name of the corresponding future factory contract
*/
function getFutureFactoryName(address _futureFactory) external view returns (string memory);
/* Future platform */
/**
* @notice Register a new future platform in the registry
* @param _futureFactory the address of the future factory
* @param _futurePlatformName the name of the future platform
* @param _future the address of the future contract logic
* @param _futureWallet the address of the future wallet contract logic
* @param _futureVault the name of the future vault contract logic
*/
function addFuturePlatform(
address _futureFactory,
string memory _futurePlatformName,
address _future,
address _futureWallet,
address _futureVault
) external;
/**
* @notice Getter to check if a future platform is registered
* @param _futurePlatformName the name of the future platform to check the registration of
* @return true if it is, false otherwise
*/
function isRegisteredFuturePlatform(string memory _futurePlatformName) external view returns (bool);
/**
* @notice Getter for the future platform contracts
* @param _futurePlatformName the name of the future platform
* @return the addresses of 0) the future logic 1) the future wallet logic 2) the future vault logic
*/
function getFuturePlatform(string memory _futurePlatformName) external view returns (address[3] memory);
/**
* @notice Getter the total count of future platftroms registered
* @return the number of future platforms registered
*/
function futurePlatformsCount() external view returns (uint256);
/**
* @notice Getter the list of platforms names registered
* @return the list of platform names registered
*/
function getFuturePlatformNames() external view returns (string[] memory);
/**
* @notice Remove a future platform from the registry
* @param _futurePlatformName the name of the future platform to remove from the registry
*/
function removeFuturePlatform(string memory _futurePlatformName) external;
/* Futures */
/**
* @notice Add a future to the registry
* @param _future the address of the future to add to the registry
*/
function addFuture(address _future) external;
/**
* @notice Remove a future from the registry
* @param _future the address of the future to remove from the registry
*/
function removeFuture(address _future) external;
/**
* @notice Getter to check if a future is registered
* @param _future the address of the future to check the registration of
* @return true if it is, false otherwise
*/
function isRegisteredFuture(address _future) external view returns (bool);
/**
* @notice Getter for the future registered at an index
* @param _index the index of the future to return
* @return the address of the corresponding future
*/
function getFutureAt(uint256 _index) external view returns (address);
/**
* @notice Getter for number of future registered
* @return the number of future registered
*/
function futureCount() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
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 EnumerableSetUpgradeable {
// 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(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));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with 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 ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
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;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface ERC20 is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external returns (string memory);
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. 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() external returns (uint8);
/**
* @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) external returns (bool);
/**
* @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) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @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);
} | * @notice Set apwibt address @param _apwibt the address of the new apwibt @dev used only for exceptional purpose/ | function setAPWIBT(address _apwibt) public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not allowed to set the apwibt");
apwibt = IAPWineIBT(_apwibt);
emit APWIBTSet(_apwibt);
}
| 5,944,939 | [
1,
694,
513,
91,
495,
88,
1758,
225,
389,
438,
91,
495,
88,
326,
1758,
434,
326,
394,
513,
91,
495,
88,
225,
1399,
1338,
364,
1520,
287,
13115,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
444,
2203,
59,
13450,
56,
12,
2867,
389,
438,
91,
495,
88,
13,
1071,
288,
203,
3639,
2583,
12,
5332,
2996,
12,
15468,
67,
16256,
16,
1234,
18,
15330,
3631,
315,
11095,
353,
486,
2935,
358,
444,
326,
513,
91,
495,
88,
8863,
203,
3639,
513,
91,
495,
88,
273,
467,
2203,
59,
558,
13450,
56,
24899,
438,
91,
495,
88,
1769,
203,
3639,
3626,
14410,
59,
13450,
56,
694,
24899,
438,
91,
495,
88,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ABDKMath64x64.sol";
/**
* @title SplytStaking
* @dev Enables a user to stake tokens into this smart contract
*/
contract SplytStaking is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 private _token; // The token to be used in this smart contract
struct Compound {
uint depositStartBlock; // Block where users are allowed to start deposits
uint depositEndBlock; // Block where deposits are no longer allowed
uint interestStartBlock; // Block that starts yield gaining
uint interestEndBlock; // Block that ends yield gained
uint startTime; // Time to start computing compound yield
uint endTime; // Time to stop computing compound yield
uint apyPerSec; // Interval at which yield compounds, e.g., 31556952 seconds/year, 8600 hours/year
uint apyPerBlock; // Reward per block. We assume 15s per block
}
Compound private compound; // Struct to hold compound information
uint constant secondsPerYear = 31556952; // Seconds in a year
uint constant blocksPerMonth = 175200; // Blocks per month and max amount of blocks allowed for reward
uint constant secondPerBlock = 15; // Number of seconds between blocks mined
uint totalPrincipal; // Total amount of token principal deposited into this smart contract
uint numUsersWithDeposits; // Total number of users who have deposited tokens into this smart contract
uint feeDivisor = 10**3; // Withdrawal fee (0.1%)
mapping (address => uint256) public _balances; // Balance of tokens by user
/**
* @dev Emitted when `_amount` tokens are staked by `_userAddress`
*/
event TokenStaked(address _userAddress, uint256 _amount);
/**
* @dev Emitted when `_amount` tokens are withdrawn by `_userAddress`
*/
event TokenWithdrawn(address _userAddress, uint256 _amount);
/**
* @dev Creates the SplytStaking smart contract
* @param token address of the token to be vested
* @param _apyPerSec APY gained per second ratio
* @param _depositStartBlock Block where deposits start
* @param _depositEndBlock Block where deposits end
*/
constructor (address token, uint _apyPerSec, uint _depositStartBlock, uint _depositEndBlock) public {
_token = IERC20(token);
// Compute start and end blocks for yield compounding
uint interestStartBlock = _depositEndBlock.add(1);
uint interestEndBlock = interestStartBlock.add(blocksPerMonth);
// Compute start and end times for the same time period
uint blocksUntilInterestStarts = interestStartBlock.sub(block.number);
uint interestStartTime = block.timestamp.add(blocksUntilInterestStarts.mul(secondPerBlock));
uint blocksUntilInterestEnd = interestEndBlock.sub(interestStartBlock);
uint interestEndTime = block.timestamp.add(blocksUntilInterestEnd.mul(secondPerBlock));
compound = Compound({
depositStartBlock: _depositStartBlock,
depositEndBlock: _depositEndBlock,
interestStartBlock: interestStartBlock,
interestEndBlock: interestEndBlock,
startTime: interestStartTime,
endTime: interestEndTime,
apyPerSec: _apyPerSec,
apyPerBlock: _apyPerSec.mul(secondPerBlock)
});
}
// -----------------------------------------------------------------------
// Modifiers
// -----------------------------------------------------------------------
/**
* @dev Modifier that only lets the function continue if it is within the deposit window (depositStartBlock, depositEndBlock)
*/
modifier depositWindow() {
require (block.number > compound.depositStartBlock && block.number <= compound.depositEndBlock, "DepositWindow: Can be called only during deposit window");
_;
}
// -----------------------------------------------------------------------
// Helpers
// -----------------------------------------------------------------------
/**
* @dev Check that the amount of blocks staked does not exceed limit: blocksPerMonth=maxBlock.
* @dev If a user keeps their tokens longer than maxBlock, they only get yield up to maxBlock.
* @param numBlocksPassed Amount of blocks passed
* @param maxBlock Highest amount of blocks allowed to pass (limit)
*/
function _blocksStaked(uint numBlocksPassed, uint maxBlock) public pure returns (uint) {
if(numBlocksPassed >= maxBlock) {
return maxBlock;
} else {
return numBlocksPassed;
}
}
// -----------------------------------------------------------------------
// COMPUTATIONS
// -----------------------------------------------------------------------
/**
* @dev Estimates the power computation
* @param x base
* @param n duration
*/
function pow (int128 x, uint n) public pure returns (int128 r) {
r = ABDKMath64x64.fromUInt (1); while (n > 0) {
if (n % 2 == 1) {
r = ABDKMath64x64.mul (r, x);
n -= 1;
} else {
x = ABDKMath64x64.mul (x, x);
n /= 2;
}
}
}
/**
* @dev Method to compute APY gained. Note: this is only used for comparison, not actually used to compute real gain
* @param principal Principal provided
* @param ratio Amount of APY gained per second
* @param n Duration
*/
function compoundInterestByTime(uint principal, uint ratio, uint n) public pure returns (uint) {
return ABDKMath64x64.mulu (
pow (
ABDKMath64x64.add (ABDKMath64x64.fromUInt (1), ABDKMath64x64.divu (ratio, 10**18)),
n),
principal);
}
/**
* @dev Wrapper method that is bound to the smart contract apyPerSec variable
* @dev Enables durations to be set manually
* @dev Not used to compute real gain
* @param principal Principal provided
* @param duration Duration
* @return the amount gained: principal + yield
*/
function compoundWithPrincipalAndTime(uint principal, uint duration) external view returns (uint) {
return compoundInterestByTime(principal, compound.apyPerSec, duration);
}
/**
* @dev Wrapper method that is bound to the smart contract apyPerSec and computes duration against live blockchain data
* @dev Not used to compute real gain
* @param principal Principal provided
* @return the amount gained: principal + yield
*/
function compoundWithPrincipal(uint principal) public view returns (uint) {
uint duration = block.timestamp - compound.startTime;
return compoundInterestByTime(principal, compound.apyPerSec, duration);
}
/**
* @dev Wrapper method that computes gain using the callers information
* @dev Uses all predefined variables in the smart contract and blockchain state
* @dev Not used to compute real gain
* @return the amount gained: principal + yield
*/
function compoundWithPrincipalByUser() external view returns (uint) {
return compoundWithPrincipal(_balances[msg.sender]);
}
/**
* @dev Raw method that computes gain using blocks instead of time
* @param principal Principal provided
* @param blocksStaked Number of blocks with which to compute gain
* @return the amount gained: principal + yield
*/
function _compoundInterestByBlock(uint principal, uint blocksStaked) public view returns (uint) {
uint reward = SafeMath.div(compound.apyPerBlock.mul(principal).mul(blocksStaked), 10**18);
return reward.add(principal);
}
/**
* @dev Computes yield gained using block raw function
* @dev Makes sure that a user cannot gain more yield than blocksPerMonth as defined in the smart contract
* @param principal Principal
* @return the amount gained: principal + yield
*/
function compoundInterestByBlock(uint principal) public view returns (uint) {
uint numBlocksPassed = block.number.sub(compound.interestStartBlock);
uint blocksStaked = _blocksStaked(numBlocksPassed, blocksPerMonth);
return _compoundInterestByBlock(principal, blocksStaked);
}
// -----------------------------------------------------------------------
// GETTERS
// -----------------------------------------------------------------------
/**
* @dev Gets block and time information out of the smart contract
* @return _currentBlock Current block on the blockchain
* @return _depositStartBlock Block where deposits are allowed
* @return _depositEndBlock Block where deposits are no longer allowed
* @return _interestStartBlock Block where yield starts growing
* @return _interestEndBlock Block where yield stops growing
* @return _interestStartTime Estimated yield start time (for comparison only)
* @return _interestEndTime Estimated yield end time (for comparison only)
* @return _interestApyPerSec APY per second rate defined in the smart contract
* @return _interestApyPerBlock APY per block defined in the smart contract
*/
function getCompoundInfo() external view returns (
uint _currentBlock,
uint _depositStartBlock,
uint _depositEndBlock,
uint _interestStartBlock,
uint _interestEndBlock,
uint _interestStartTime,
uint _interestEndTime,
uint _interestApyPerSec,
uint _interestApyPerBlock
) {
return (
block.number,
compound.depositStartBlock,
compound.depositEndBlock,
compound.interestStartBlock,
compound.interestEndBlock,
compound.startTime,
compound.endTime,
compound.apyPerSec,
compound.apyPerBlock
);
}
/**
* @dev Gets staking data from this smart contract
* @return _totalPrincipal Total amount of tokens deposited as principal
* @return _numUsersWithDeposits Number of users who have staked into this smart contract
*/
function getAdminStakingInfo() public view returns (uint _totalPrincipal, uint _numUsersWithDeposits) {
return (totalPrincipal, numUsersWithDeposits);
}
/**
* @dev Gets user balance data
* @dev If this is called before any yield is gained, we manually display 0 reward
* @param userAddress Address of a given user
* @return _principal Principal that a user has staked
* @return _reward Current estimated reward earned
* @return _balance Total balance (_principal + _reward)
*/
function getUserBalances(address userAddress) external view returns (uint _principal, uint _reward, uint _balance) {
if(block.number <= compound.interestStartBlock) {
return (
_balances[userAddress],
0,
_balances[userAddress]);
} else {
uint totalBalance = compoundInterestByBlock(_balances[userAddress]);
uint reward = totalBalance.sub(_balances[userAddress]);
return (
_balances[userAddress],
reward,
totalBalance
);
}
}
/**
* @dev Reads the APY defined in the smart contract as a percentage
* @return _apy APY in percentage form
*/
function apy() external view returns (uint _apy) {
return secondsPerYear * compound.apyPerSec * 100;
}
// -----------------------------------------------------------------------
// SETTERS
// -----------------------------------------------------------------------
/**
* @dev Enables the deposit window to be changed. Only the smart contract owner is allowed to do this
* @dev Because blocks are not always found at the same rate, we may need to change the deposit window so events start on time
* @dev We will only call this so the start time is as accurate as possible
* @dev We have to recompute the yield start block and yield end block times as well
* @param _depositStartBlock New deposit start block
* @param _depositEndBlock New deposit end block
*/
function changeDepositWindow(uint _depositStartBlock, uint _depositEndBlock) external onlyOwner {
compound.depositStartBlock = _depositStartBlock;
compound.depositEndBlock = _depositEndBlock;
compound.interestStartBlock = _depositEndBlock.add(1);
compound.interestEndBlock = compound.interestStartBlock.add(blocksPerMonth);
uint blocksUntilInterestStarts = compound.interestStartBlock.sub(block.number);
compound.startTime = block.timestamp.add(blocksUntilInterestStarts.mul(secondPerBlock));
uint blocksUntilInterestEnd = compound.interestEndBlock.sub(compound.interestStartBlock);
compound.endTime = block.timestamp.add(blocksUntilInterestEnd.mul(secondPerBlock));
}
/**
* @dev Enables a user to deposit their stake into this smart contract. A user must call approve tokens before calling this method
* @dev This can only be called during the deposit window. Calling this before or after will fail
* @dev We also make sure to track the state of [totalPrincipal, numUsersWithDeposits]
* @param _amount The amount of tokens to stake into this smart contract
*/
function stakeTokens(uint _amount) external depositWindow {
require(_token.allowance(msg.sender, address(this)) >= _amount, "TokenBalance: User has not allowed tokens to be used");
require(_token.balanceOf(msg.sender) >= _amount, "TokenBalance: msg.sender can not stake more than they have");
if(_balances[msg.sender] == 0) {
numUsersWithDeposits += 1;
}
_balances[msg.sender] += _amount;
totalPrincipal += _amount;
require(_token.transferFrom(msg.sender,address(this), _amount), "TokenTransfer: failed to transfer tokens from msg.sender here");
emit TokenStaked(msg.sender, _amount);
}
/**
* @dev Lets a user withdraw all their tokens from this smart contract
* @dev A fee is charged on all withdrawals
* @dev We make sure to track the state of [totalPrincipal, numUsersWithDeposits]
*/
function withdrawTokens() external {
require(_balances[msg.sender] > 0, "TokenBalance: no tokens available to be withdrawn");
uint totalBalance = 0;
if(block.number <= compound.depositEndBlock) {
totalBalance = _balances[msg.sender];
} else {
totalBalance = compoundInterestByBlock(_balances[msg.sender]);
}
uint fee = totalBalance.div(feeDivisor);
totalBalance = totalBalance.sub(fee);
totalPrincipal -= _balances[msg.sender];
_balances[msg.sender] = 0;
numUsersWithDeposits -= 1;
require(_token.transfer(msg.sender, totalBalance));
emit TokenWithdrawn(msg.sender, totalBalance);
}
/**
* @dev Computes the amount of tokens the owner is allowed to withdraw
* @dev Assumes owner deposited tokens at the end of the deposit window, and not all users stay for the full 30 days
* @dev There will be a remainder because users leave before the 30 days is over. Owner withdraws the balance
*/
function adminWithdrawRemaining() external onlyOwner {
uint totalBalanceNeeded = compoundInterestByBlock(totalPrincipal);
uint contractBalance = _token.balanceOf(address(this));
// We deposit tokens and assume everyone gains yield for the full 30 days
// There is a difference because some users will withdraw tokens before the 30 days is over
if(contractBalance > totalBalanceNeeded) {
uint extraTokenBalance = contractBalance.sub(totalBalanceNeeded);
require(_token.transfer(msg.sender, extraTokenBalance));
emit TokenWithdrawn(msg.sender, extraTokenBalance);
}
}
/**
* @dev Lets owner, and only the owner, withdraw any amount of tokens
* @dev ONLY TO BE CALLED IN A CATASTROPHIC SCENARIO!!!
* @param _amount Number of tokens to withdraw
*/
function withdrawExtraTokens(uint _amount) external onlyOwner {
require(_token.transfer(msg.sender, _amount));
emit TokenWithdrawn(msg.sender, _amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
// 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) {
unchecked {
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) {
unchecked {
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) {
return a + b;
}
/**
* @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 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) {
return a * b;
}
/**
* @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.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
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) {
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) {
unchecked {
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.
*
* 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) {
unchecked {
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) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_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);
}
}
// SPDX-License-Identifier: BSD-4-Clause
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.8.0;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt (int256 x) internal pure returns (int128) {
unchecked {
require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt (int128 x) internal pure returns (int64) {
unchecked {
return int64 (x >> 64);
}
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt (uint256 x) internal pure returns (int128) {
unchecked {
require (x <= 0x7FFFFFFFFFFFFFFF);
return int128 (int256 (x << 64));
}
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt (int128 x) internal pure returns (uint64) {
unchecked {
require (x >= 0);
return uint64 (uint128 (x >> 64));
}
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128 (int256 x) internal pure returns (int128) {
unchecked {
int256 result = x >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128 (int128 x) internal pure returns (int256) {
unchecked {
return int256 (x) << 64;
}
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add (int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 result = int256(x) + y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub (int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 result = int256(x) - y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul (int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 result = int256(x) * y >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli (int128 x, int256 y) internal pure returns (int256) {
unchecked {
if (x == MIN_64x64) {
require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu (x, uint256 (y));
if (negativeResult) {
require (absoluteResult <=
0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (absoluteResult);
}
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu (int128 x, uint256 y) internal pure returns (uint256) {
unchecked {
if (y == 0) return 0;
require (x >= 0);
uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256 (int256 (x)) * (y >> 128);
require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require (hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div (int128 x, int128 y) internal pure returns (int128) {
unchecked {
require (y != 0);
int256 result = (int256 (x) << 64) / y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi (int256 x, int256 y) internal pure returns (int128) {
unchecked {
require (y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu (uint256 (x), uint256 (y));
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu (uint256 x, uint256 y) internal pure returns (int128) {
unchecked {
require (y != 0);
uint128 result = divuu (x, y);
require (result <= uint128 (MAX_64x64));
return int128 (result);
}
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg (int128 x) internal pure returns (int128) {
unchecked {
require (x != MIN_64x64);
return -x;
}
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs (int128 x) internal pure returns (int128) {
unchecked {
require (x != MIN_64x64);
return x < 0 ? -x : x;
}
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv (int128 x) internal pure returns (int128) {
unchecked {
require (x != 0);
int256 result = int256 (0x100000000000000000000000000000000) / x;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg (int128 x, int128 y) internal pure returns (int128) {
unchecked {
return int128 ((int256 (x) + int256 (y)) >> 1);
}
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg (int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 m = int256 (x) * int256 (y);
require (m >= 0);
require (m <
0x4000000000000000000000000000000000000000000000000000000000000000);
return int128 (sqrtu (uint256 (m)));
}
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow (int128 x, uint256 y) internal pure returns (int128) {
unchecked {
bool negative = x < 0 && y & 1 == 1;
uint256 absX = uint128 (x < 0 ? -x : x);
uint256 absResult;
absResult = 0x100000000000000000000000000000000;
if (absX <= 0x10000000000000000) {
absX <<= 63;
while (y != 0) {
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x2 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x4 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x8 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
y >>= 4;
}
absResult >>= 64;
} else {
uint256 absXShift = 63;
if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }
if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }
if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }
if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }
if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }
if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }
uint256 resultShift = 0;
while (y != 0) {
require (absXShift < 64);
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
resultShift += absXShift;
if (absResult > 0x100000000000000000000000000000000) {
absResult >>= 1;
resultShift += 1;
}
}
absX = absX * absX >> 127;
absXShift <<= 1;
if (absX >= 0x100000000000000000000000000000000) {
absX >>= 1;
absXShift += 1;
}
y >>= 1;
}
require (resultShift < 64);
absResult >>= 64 - resultShift;
}
int256 result = negative ? -int256 (absResult) : int256 (absResult);
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt (int128 x) internal pure returns (int128) {
unchecked {
require (x >= 0);
return int128 (sqrtu (uint256 (int256 (x)) << 64));
}
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2 (int128 x) internal pure returns (int128) {
unchecked {
require (x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = msb - 64 << 64;
uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256 (b);
}
return int128 (result);
}
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln (int128 x) internal pure returns (int128) {
unchecked {
require (x > 0);
return int128 (int256 (
uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));
}
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2 (int128 x) internal pure returns (int128) {
unchecked {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (x & 0x4000000000000000 > 0)
result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (x & 0x2000000000000000 > 0)
result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (x & 0x1000000000000000 > 0)
result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (x & 0x800000000000000 > 0)
result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (x & 0x400000000000000 > 0)
result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (x & 0x200000000000000 > 0)
result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (x & 0x100000000000000 > 0)
result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (x & 0x80000000000000 > 0)
result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (x & 0x40000000000000 > 0)
result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (x & 0x20000000000000 > 0)
result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (x & 0x10000000000000 > 0)
result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (x & 0x8000000000000 > 0)
result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (x & 0x4000000000000 > 0)
result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (x & 0x2000000000000 > 0)
result = result * 0x1000162E525EE054754457D5995292026 >> 128;
if (x & 0x1000000000000 > 0)
result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (x & 0x800000000000 > 0)
result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (x & 0x400000000000 > 0)
result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (x & 0x200000000000 > 0)
result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (x & 0x100000000000 > 0)
result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (x & 0x80000000000 > 0)
result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (x & 0x40000000000 > 0)
result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (x & 0x20000000000 > 0)
result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (x & 0x10000000000 > 0)
result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (x & 0x8000000000 > 0)
result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (x & 0x4000000000 > 0)
result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (x & 0x2000000000 > 0)
result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (x & 0x1000000000 > 0)
result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (x & 0x800000000 > 0)
result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (x & 0x400000000 > 0)
result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (x & 0x200000000 > 0)
result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (x & 0x100000000 > 0)
result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (x & 0x80000000 > 0)
result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (x & 0x40000000 > 0)
result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (x & 0x20000000 > 0)
result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (x & 0x10000000 > 0)
result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (x & 0x8000000 > 0)
result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (x & 0x4000000 > 0)
result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (x & 0x2000000 > 0)
result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (x & 0x1000000 > 0)
result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (x & 0x800000 > 0)
result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (x & 0x400000 > 0)
result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (x & 0x200000 > 0)
result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (x & 0x100000 > 0)
result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (x & 0x80000 > 0)
result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (x & 0x40000 > 0)
result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (x & 0x20000 > 0)
result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (x & 0x10000 > 0)
result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (x & 0x8000 > 0)
result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (x & 0x4000 > 0)
result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (x & 0x2000 > 0)
result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (x & 0x1000 > 0)
result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (x & 0x800 > 0)
result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (x & 0x400 > 0)
result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (x & 0x200 > 0)
result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (x & 0x100 > 0)
result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (x & 0x80 > 0)
result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (x & 0x40 > 0)
result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (x & 0x20 > 0)
result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
if (x & 0x10 > 0)
result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (x & 0x8 > 0)
result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (x & 0x4 > 0)
result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (x & 0x2 > 0)
result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (x & 0x1 > 0)
result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;
result >>= uint256 (int256 (63 - (x >> 64)));
require (result <= uint256 (int256 (MAX_64x64)));
return int128 (int256 (result));
}
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp (int128 x) internal pure returns (int128) {
unchecked {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2 (
int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu (uint256 x, uint256 y) private pure returns (uint128) {
unchecked {
require (y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert (xh == hi >> 128);
result += xl / y;
}
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128 (result);
}
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu (uint256 x) private pure returns (uint128) {
unchecked {
if (x == 0) return 0;
else {
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }
if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }
if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }
if (xx >= 0x10000) { xx >>= 16; r <<= 8; }
if (xx >= 0x100) { xx >>= 8; r <<= 4; }
if (xx >= 0x10) { xx >>= 4; r <<= 2; }
if (xx >= 0x8) { r <<= 1; }
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return uint128 (r < r1 ? r : r1);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
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);
}
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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
| * @title SplytStaking @dev Enables a user to stake tokens into this smart contract/ | contract SplytStaking is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
pragma solidity 0.8.0;
struct Compound {
}
event TokenStaked(address _userAddress, uint256 _amount);
event TokenWithdrawn(address _userAddress, uint256 _amount);
constructor (address token, uint _apyPerSec, uint _depositStartBlock, uint _depositEndBlock) public {
_token = IERC20(token);
uint interestStartBlock = _depositEndBlock.add(1);
uint interestEndBlock = interestStartBlock.add(blocksPerMonth);
uint blocksUntilInterestStarts = interestStartBlock.sub(block.number);
uint interestStartTime = block.timestamp.add(blocksUntilInterestStarts.mul(secondPerBlock));
uint blocksUntilInterestEnd = interestEndBlock.sub(interestStartBlock);
uint interestEndTime = block.timestamp.add(blocksUntilInterestEnd.mul(secondPerBlock));
compound = Compound({
depositStartBlock: _depositStartBlock,
depositEndBlock: _depositEndBlock,
interestStartBlock: interestStartBlock,
interestEndBlock: interestEndBlock,
startTime: interestStartTime,
endTime: interestEndTime,
apyPerSec: _apyPerSec,
apyPerBlock: _apyPerSec.mul(secondPerBlock)
});
}
constructor (address token, uint _apyPerSec, uint _depositStartBlock, uint _depositEndBlock) public {
_token = IERC20(token);
uint interestStartBlock = _depositEndBlock.add(1);
uint interestEndBlock = interestStartBlock.add(blocksPerMonth);
uint blocksUntilInterestStarts = interestStartBlock.sub(block.number);
uint interestStartTime = block.timestamp.add(blocksUntilInterestStarts.mul(secondPerBlock));
uint blocksUntilInterestEnd = interestEndBlock.sub(interestStartBlock);
uint interestEndTime = block.timestamp.add(blocksUntilInterestEnd.mul(secondPerBlock));
compound = Compound({
depositStartBlock: _depositStartBlock,
depositEndBlock: _depositEndBlock,
interestStartBlock: interestStartBlock,
interestEndBlock: interestEndBlock,
startTime: interestStartTime,
endTime: interestEndTime,
apyPerSec: _apyPerSec,
apyPerBlock: _apyPerSec.mul(secondPerBlock)
});
}
modifier depositWindow() {
require (block.number > compound.depositStartBlock && block.number <= compound.depositEndBlock, "DepositWindow: Can be called only during deposit window");
_;
}
function _blocksStaked(uint numBlocksPassed, uint maxBlock) public pure returns (uint) {
if(numBlocksPassed >= maxBlock) {
return maxBlock;
return numBlocksPassed;
}
}
function _blocksStaked(uint numBlocksPassed, uint maxBlock) public pure returns (uint) {
if(numBlocksPassed >= maxBlock) {
return maxBlock;
return numBlocksPassed;
}
}
} else {
function pow (int128 x, uint n) public pure returns (int128 r) {
r = ABDKMath64x64.fromUInt (1); while (n > 0) {
if (n % 2 == 1) {
r = ABDKMath64x64.mul (r, x);
n -= 1;
x = ABDKMath64x64.mul (x, x);
n /= 2;
}
}
}
function pow (int128 x, uint n) public pure returns (int128 r) {
r = ABDKMath64x64.fromUInt (1); while (n > 0) {
if (n % 2 == 1) {
r = ABDKMath64x64.mul (r, x);
n -= 1;
x = ABDKMath64x64.mul (x, x);
n /= 2;
}
}
}
function pow (int128 x, uint n) public pure returns (int128 r) {
r = ABDKMath64x64.fromUInt (1); while (n > 0) {
if (n % 2 == 1) {
r = ABDKMath64x64.mul (r, x);
n -= 1;
x = ABDKMath64x64.mul (x, x);
n /= 2;
}
}
}
} else {
function compoundInterestByTime(uint principal, uint ratio, uint n) public pure returns (uint) {
return ABDKMath64x64.mulu (
pow (
ABDKMath64x64.add (ABDKMath64x64.fromUInt (1), ABDKMath64x64.divu (ratio, 10**18)),
n),
principal);
}
function compoundWithPrincipalAndTime(uint principal, uint duration) external view returns (uint) {
return compoundInterestByTime(principal, compound.apyPerSec, duration);
}
function compoundWithPrincipal(uint principal) public view returns (uint) {
uint duration = block.timestamp - compound.startTime;
return compoundInterestByTime(principal, compound.apyPerSec, duration);
}
function compoundWithPrincipalByUser() external view returns (uint) {
return compoundWithPrincipal(_balances[msg.sender]);
}
function _compoundInterestByBlock(uint principal, uint blocksStaked) public view returns (uint) {
uint reward = SafeMath.div(compound.apyPerBlock.mul(principal).mul(blocksStaked), 10**18);
return reward.add(principal);
}
function compoundInterestByBlock(uint principal) public view returns (uint) {
uint numBlocksPassed = block.number.sub(compound.interestStartBlock);
uint blocksStaked = _blocksStaked(numBlocksPassed, blocksPerMonth);
return _compoundInterestByBlock(principal, blocksStaked);
}
function getCompoundInfo() external view returns (
uint _currentBlock,
uint _depositStartBlock,
uint _depositEndBlock,
uint _interestStartBlock,
uint _interestEndBlock,
uint _interestStartTime,
uint _interestEndTime,
uint _interestApyPerSec,
uint _interestApyPerBlock
) {
return (
block.number,
compound.depositStartBlock,
compound.depositEndBlock,
compound.interestStartBlock,
compound.interestEndBlock,
compound.startTime,
compound.endTime,
compound.apyPerSec,
compound.apyPerBlock
);
}
function getAdminStakingInfo() public view returns (uint _totalPrincipal, uint _numUsersWithDeposits) {
return (totalPrincipal, numUsersWithDeposits);
}
function getUserBalances(address userAddress) external view returns (uint _principal, uint _reward, uint _balance) {
if(block.number <= compound.interestStartBlock) {
return (
_balances[userAddress],
0,
_balances[userAddress]);
uint totalBalance = compoundInterestByBlock(_balances[userAddress]);
uint reward = totalBalance.sub(_balances[userAddress]);
return (
_balances[userAddress],
reward,
totalBalance
);
}
}
function getUserBalances(address userAddress) external view returns (uint _principal, uint _reward, uint _balance) {
if(block.number <= compound.interestStartBlock) {
return (
_balances[userAddress],
0,
_balances[userAddress]);
uint totalBalance = compoundInterestByBlock(_balances[userAddress]);
uint reward = totalBalance.sub(_balances[userAddress]);
return (
_balances[userAddress],
reward,
totalBalance
);
}
}
} else {
function apy() external view returns (uint _apy) {
return secondsPerYear * compound.apyPerSec * 100;
}
function changeDepositWindow(uint _depositStartBlock, uint _depositEndBlock) external onlyOwner {
compound.depositStartBlock = _depositStartBlock;
compound.depositEndBlock = _depositEndBlock;
compound.interestStartBlock = _depositEndBlock.add(1);
compound.interestEndBlock = compound.interestStartBlock.add(blocksPerMonth);
uint blocksUntilInterestStarts = compound.interestStartBlock.sub(block.number);
compound.startTime = block.timestamp.add(blocksUntilInterestStarts.mul(secondPerBlock));
uint blocksUntilInterestEnd = compound.interestEndBlock.sub(compound.interestStartBlock);
compound.endTime = block.timestamp.add(blocksUntilInterestEnd.mul(secondPerBlock));
}
function stakeTokens(uint _amount) external depositWindow {
require(_token.allowance(msg.sender, address(this)) >= _amount, "TokenBalance: User has not allowed tokens to be used");
require(_token.balanceOf(msg.sender) >= _amount, "TokenBalance: msg.sender can not stake more than they have");
if(_balances[msg.sender] == 0) {
numUsersWithDeposits += 1;
}
_balances[msg.sender] += _amount;
totalPrincipal += _amount;
require(_token.transferFrom(msg.sender,address(this), _amount), "TokenTransfer: failed to transfer tokens from msg.sender here");
emit TokenStaked(msg.sender, _amount);
}
function stakeTokens(uint _amount) external depositWindow {
require(_token.allowance(msg.sender, address(this)) >= _amount, "TokenBalance: User has not allowed tokens to be used");
require(_token.balanceOf(msg.sender) >= _amount, "TokenBalance: msg.sender can not stake more than they have");
if(_balances[msg.sender] == 0) {
numUsersWithDeposits += 1;
}
_balances[msg.sender] += _amount;
totalPrincipal += _amount;
require(_token.transferFrom(msg.sender,address(this), _amount), "TokenTransfer: failed to transfer tokens from msg.sender here");
emit TokenStaked(msg.sender, _amount);
}
function withdrawTokens() external {
require(_balances[msg.sender] > 0, "TokenBalance: no tokens available to be withdrawn");
uint totalBalance = 0;
if(block.number <= compound.depositEndBlock) {
totalBalance = _balances[msg.sender];
totalBalance = compoundInterestByBlock(_balances[msg.sender]);
}
uint fee = totalBalance.div(feeDivisor);
totalBalance = totalBalance.sub(fee);
totalPrincipal -= _balances[msg.sender];
_balances[msg.sender] = 0;
numUsersWithDeposits -= 1;
require(_token.transfer(msg.sender, totalBalance));
emit TokenWithdrawn(msg.sender, totalBalance);
}
function withdrawTokens() external {
require(_balances[msg.sender] > 0, "TokenBalance: no tokens available to be withdrawn");
uint totalBalance = 0;
if(block.number <= compound.depositEndBlock) {
totalBalance = _balances[msg.sender];
totalBalance = compoundInterestByBlock(_balances[msg.sender]);
}
uint fee = totalBalance.div(feeDivisor);
totalBalance = totalBalance.sub(fee);
totalPrincipal -= _balances[msg.sender];
_balances[msg.sender] = 0;
numUsersWithDeposits -= 1;
require(_token.transfer(msg.sender, totalBalance));
emit TokenWithdrawn(msg.sender, totalBalance);
}
} else {
function adminWithdrawRemaining() external onlyOwner {
uint totalBalanceNeeded = compoundInterestByBlock(totalPrincipal);
uint contractBalance = _token.balanceOf(address(this));
if(contractBalance > totalBalanceNeeded) {
uint extraTokenBalance = contractBalance.sub(totalBalanceNeeded);
require(_token.transfer(msg.sender, extraTokenBalance));
emit TokenWithdrawn(msg.sender, extraTokenBalance);
}
}
function adminWithdrawRemaining() external onlyOwner {
uint totalBalanceNeeded = compoundInterestByBlock(totalPrincipal);
uint contractBalance = _token.balanceOf(address(this));
if(contractBalance > totalBalanceNeeded) {
uint extraTokenBalance = contractBalance.sub(totalBalanceNeeded);
require(_token.transfer(msg.sender, extraTokenBalance));
emit TokenWithdrawn(msg.sender, extraTokenBalance);
}
}
function withdrawExtraTokens(uint _amount) external onlyOwner {
require(_token.transfer(msg.sender, _amount));
emit TokenWithdrawn(msg.sender, _amount);
}
}
| 13,714,877 | [
1,
55,
1283,
88,
510,
6159,
225,
1374,
1538,
279,
729,
358,
384,
911,
2430,
1368,
333,
13706,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
348,
1283,
88,
510,
6159,
353,
14223,
6914,
288,
203,
225,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
225,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
20,
31,
203,
225,
1958,
21327,
288,
203,
225,
289,
203,
203,
203,
203,
203,
203,
225,
871,
3155,
510,
9477,
12,
2867,
389,
1355,
1887,
16,
2254,
5034,
389,
8949,
1769,
203,
225,
871,
3155,
1190,
9446,
82,
12,
2867,
389,
1355,
1887,
16,
2254,
5034,
389,
8949,
1769,
203,
225,
3885,
261,
2867,
1147,
16,
2254,
389,
438,
93,
2173,
2194,
16,
2254,
389,
323,
1724,
1685,
1768,
16,
2254,
389,
323,
1724,
1638,
1768,
13,
1071,
288,
203,
565,
389,
2316,
273,
467,
654,
39,
3462,
12,
2316,
1769,
203,
203,
565,
2254,
16513,
1685,
1768,
273,
389,
323,
1724,
1638,
1768,
18,
1289,
12,
21,
1769,
203,
565,
2254,
16513,
1638,
1768,
273,
16513,
1685,
1768,
18,
1289,
12,
7996,
2173,
5445,
1769,
203,
203,
565,
2254,
4398,
9716,
29281,
11203,
273,
16513,
1685,
1768,
18,
1717,
12,
2629,
18,
2696,
1769,
203,
565,
2254,
16513,
13649,
273,
1203,
18,
5508,
18,
1289,
12,
7996,
9716,
29281,
11203,
18,
16411,
12,
8538,
2173,
1768,
10019,
203,
565,
2254,
4398,
9716,
29281,
1638,
273,
16513,
1638,
1768,
18,
1717,
12,
2761,
395,
1685,
1768,
1769,
203,
565,
2254,
16513,
25255,
273,
1203,
18,
5508,
18,
1289,
12,
7996,
9716,
29281,
1638,
18,
16411,
12,
8538,
2173,
1768,
10019,
2
]
|
/**
*Submitted for verification at Etherscan.io on 2021-09-05
*/
/**
*Submitted for verification at Etherscan.io on 2021-08-27
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface 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 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;
}
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
}
/*
* @dev 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;
}
}
/**
* @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(), "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), "zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
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, "insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "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, "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, "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, "insufficient balance");
require(isContract(target), "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, "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), "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, "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), "non-contract");
(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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "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), "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), "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 = ERC721.ownerOf(tokenId);
require(to != owner, "approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"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), "nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "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), "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), "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), "non 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), "nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"non 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), "zero address");
require(!_exists(tokenId), "already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "not own");
require(to != address(0), "zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("non 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 {}
}
/**
* @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);
}
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
contract ColorfulLoot is ERC721Enumerable, ReentrancyGuard, Ownable {
using Strings for uint256;
string[] private weapons = [
"Gyrm Axe",
"Long Bow",
"Malformed Claws",
"Old Knight Hammer",
"Spitfire Spear",
"Broadsword",
"Black Scorpion Stinger",
"Mail Breaker",
"Archdrake Staff",
"Protective Chime",
"Notched Whip",
"Old Knight Ultra Greatsword",
"Griswold's Worn Edge",
"Short Sword",
"Monster Hunter",
"Born's Searing Spite"
];
string[] private chestArmor = [
"Alonne Knight Armor",
"Mastodon Armor",
"Black Hollow Mage Robe",
"Bone King Robe",
"Northwarder Robe",
"Red Lion Warrior Cape",
"Royal Swordsman Armor",
"Singer's Dress",
"Cloth Tunic",
"Brigandine Coat",
"Aquila Cuirass",
"Banded Cuirass",
"Ring Mail",
"Plate Mail",
"Battle Armor",
"Goldskin"
];
string[] private headArmor = [
"The Undead Crown",
"Mystery Helm",
"Star Helm",
"Leather Hood",
"Helmet",
"Plated Helm",
"Crown",
"Lion Warrior Helm",
"Mad Warrior Mask",
"Moon Hat",
"Old Bell Helm",
"Old Knight Helm",
"Drakeblood Helm",
"Royal Soldier Helm"
];
string[] private waistArmor = [
"Mystery Bracers",
"Mail Bands",
"Armbands",
"Mesh Belt",
"Razorspikes",
"Ascended Bracers",
"Dragonskin Belt",
"Hard Leather Belt",
"Leather Belt",
"Demon's Animus",
"Silk Sash",
"Wool Sash",
"Linen Sash",
"Sash"
];
string[] private footArmor = [
"Holy Greaves",
"Ornate Greaves",
"Greaves",
"Chain Boots",
"Heavy Boots",
"Demonhide Boots",
"Dragonskin Boots",
"Studded Leather Boots",
"Hard Leather Boots",
"Leather Boots",
"Divine Slippers",
"Silk Slippers",
"Wool Shoes",
"Linen Shoes",
"Shoes"
];
string[] private handArmor = [
"Mystery Gloves",
"Hide Gloves",
"Chain Gloves",
"Splint Mail Gloves",
"Demon's Hands",
"Dragonskin Gloves",
"Stone Gauntlets",
"Hard Leather Gloves",
"Leather Gloves",
"Grips"
];
string[] private necklaces = [
"Necklace",
"Amulet",
"Pendant"
];
string[] private rings = [
"Gold Ring",
"Silver Ring",
"Bronze Ring",
"Hellfire Ring",
"Mystery Ring",
"Ruby Ring"
];
string[] private suffixes = [
"of Power",
"of Giants",
"of Titans",
"of Skill",
"of Perfection",
"of Brilliance",
"of Enlightenment",
"of Protection",
"of Anger",
"of Rage",
"of Fury",
"of Vitriol",
"of the Fox",
"of Detection",
"of Reflection",
"of the Twins"
];
string[] private namePrefixes = [
"Agony", "Apocalypse", "Armageddon", "Beast", "Behemoth", "Blight", "Blood", "Bramble",
"Brimstone", "Brood", "Carrion", "Cataclysm", "Chimeric", "Corpse", "Corruption", "Damnation",
"Death", "Demon", "Dire", "Dragon", "Dread", "Doom", "Dusk", "Eagle", "Empyrean", "Fate", "Foe",
"Gale", "Ghoul", "Gloom", "Glyph", "Golem", "Grim", "Hate", "Havoc", "Honour", "Horror", "Hypnotic",
"Kraken", "Loath", "Maelstrom", "Mind", "Miracle", "Morbid", "Oblivion", "Onslaught", "Pain",
"Pandemonium", "Phoenix", "Plague", "Rage", "Rapture", "Rune", "Skull", "Sol", "Soul", "Sorrow",
"Spirit", "Storm", "Tempest", "Torment", "Vengeance", "Victory", "Viper", "Vortex", "Woe", "Wrath",
"Light's", "Shimmering"
];
string[] private nameSuffixes = [
"Bane",
"Root",
"Bite",
"Song",
"Roar",
"Grasp",
"Instrument",
"Glow",
"Bender",
"Shadow",
"Whisper",
"Shout",
"Growl",
"Tear",
"Peak",
"Form",
"Sun",
"Moon"
];
function grade(uint256 rand) internal pure returns(string memory) {
uint256 greatness = rand % 100;
if (greatness >= 98) {
return "#EC6066";
} else if (greatness >= 95) {
return "#F9AE54";
} else if (greatness >= 85) {
return "#6699CC";
} else if (greatness >= 70) {
return "#99C794";
} else {
return "#D8DEE9";
}
}
function getWeapon(uint256 tokenId) public view returns (string memory) {
return pluck(getWeaponSeed(tokenId), weapons);
}
function getWeaponSeed(uint256 tokenId) internal pure returns (uint256) {
return getSeed(tokenId, "WEAPON");
}
function getChest(uint256 tokenId) public view returns (string memory) {
return pluck(getChestSeed(tokenId), chestArmor);
}
function getChestSeed(uint256 tokenId) internal pure returns (uint256) {
return getSeed(tokenId, "CHEST");
}
function getHead(uint256 tokenId) public view returns (string memory) {
return pluck(getHeadSeed(tokenId), headArmor);
}
function getHeadSeed(uint256 tokenId) internal pure returns (uint256) {
return getSeed(tokenId, "HEAD");
}
function getWaist(uint256 tokenId) public view returns (string memory) {
return pluck(getWaistSeed(tokenId), waistArmor);
}
function getWaistSeed(uint256 tokenId) internal pure returns (uint256) {
return getSeed(tokenId, "WAIST");
}
function getFoot(uint256 tokenId) public view returns (string memory) {
return pluck(getFootSeed(tokenId), footArmor);
}
function getFootSeed(uint256 tokenId) internal pure returns (uint256) {
return getSeed(tokenId, "FOOT");
}
function getHand(uint256 tokenId) public view returns (string memory) {
return pluck(getHandSeed(tokenId), handArmor);
}
function getHandSeed(uint256 tokenId) internal pure returns (uint256) {
return getSeed(tokenId, "HAND");
}
function getNeck(uint256 tokenId) public view returns (string memory) {
return pluck(getNeckSeed(tokenId), necklaces);
}
function getNeckSeed(uint256 tokenId) internal pure returns (uint256) {
return getSeed(tokenId, "NECK");
}
function getRing(uint256 tokenId) public view returns (string memory) {
return pluck(getRingSeed(tokenId), rings);
}
function getRingSeed(uint256 tokenId) internal pure returns (uint256) {
return getSeed(tokenId, "RING");
}
function getSeed(uint256 tokenId, string memory keyPrefix) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(string(abi.encodePacked(tokenId.toString(), keyPrefix)))));
}
function pluck(uint256 rand, string[] memory sourceArray) internal view returns (string memory) {
string memory output = sourceArray[rand % sourceArray.length];
uint256 greatness = rand % 100;
if (greatness > 70) {
output = string(abi.encodePacked(output, " ", suffixes[rand % suffixes.length]));
}
if (greatness >= 85) {
string[2] memory name;
name[0] = namePrefixes[rand % namePrefixes.length];
name[1] = nameSuffixes[rand % nameSuffixes.length];
if (greatness >= 98) {
output = string(abi.encodePacked('"', name[0], ' ', name[1], '" ', output, " +2"));
} else if (greatness >= 95) {
output = string(abi.encodePacked('"', name[0], ' ', name[1], '" ', output, " +1"));
} else {
output = string(abi.encodePacked('"', name[0], ' ', name[1], '" ', output));
}
}
return output;
}
function oneElement(uint256 y, uint256 seed, string[] memory sourceArray) public view returns (string memory) {
return string(abi.encodePacked('<text x="10" y="', y.toString(), '" class="base" fill="', grade(seed), '" >', pluck(seed, sourceArray), '</text>'));
}
function tokenURI(uint256 tokenId) override public view returns (string memory) {
string[10] memory parts;
parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base{font-size:11px;}</style><rect width="100%" height="100%" fill="#303841" />';
parts[1] = oneElement(20, getWeaponSeed(tokenId), weapons);
parts[2] = oneElement(40, getChestSeed(tokenId), chestArmor);
parts[3] = oneElement(60, getHeadSeed(tokenId), headArmor);
parts[4] = oneElement(80, getWaistSeed(tokenId), waistArmor);
parts[5] = oneElement(100, getFootSeed(tokenId), footArmor);
parts[6] = oneElement(120, getHandSeed(tokenId), handArmor);
parts[7] = oneElement(140, getNeckSeed(tokenId), necklaces);
parts[8] = oneElement(160, getRingSeed(tokenId), rings);
parts[9] = '</svg>';
string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5]));
output = string(abi.encodePacked(output, parts[6], parts[7], parts[8], parts[9]));
string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "ColorfulLoot #', tokenId.toString(), '", "description": "Colorful Loot is randomized adventurer gear generated and stored on chain.The rarity of gear can be distinguished by different colors.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}'))));
output = string(abi.encodePacked('data:application/json;base64,', json));
return output;
}
function claim(uint256 tokenId) public nonReentrant {
require(tokenId > 0 && tokenId < 7778, "Token ID invalid");
_safeMint(_msgSender(), tokenId);
}
function ownerClaim(uint256 tokenId) public nonReentrant onlyOwner {
require(tokenId > 7777 && tokenId < 8001, "Token ID invalid");
_safeMint(owner(), tokenId);
}
constructor() ERC721("ColorfulLoot", "CLOOT") Ownable() {}
}
/// [MIT License]
/// @title Base64
/// @notice Provides a function for encoding some bytes in base64
/// @author Brecht Devos <[email protected]>
library Base64 {
bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// @notice Encodes some bytes to the base64 representation
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
} | * @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);
constructor() {
_setOwner(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
| 6,711,122 | [
1,
8924,
1605,
1492,
8121,
279,
5337,
2006,
3325,
12860,
16,
1625,
1915,
353,
392,
2236,
261,
304,
3410,
13,
716,
848,
506,
17578,
12060,
2006,
358,
2923,
4186,
18,
2525,
805,
16,
326,
3410,
2236,
903,
506,
326,
1245,
716,
5993,
383,
1900,
326,
6835,
18,
1220,
848,
5137,
506,
3550,
598,
288,
13866,
5460,
12565,
5496,
1220,
1605,
353,
1399,
3059,
16334,
18,
2597,
903,
1221,
2319,
326,
9606,
1375,
3700,
5541,
9191,
1492,
848,
506,
6754,
358,
3433,
4186,
358,
13108,
3675,
999,
358,
326,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
17801,
6835,
14223,
6914,
353,
1772,
288,
203,
565,
1758,
3238,
389,
8443,
31,
203,
203,
565,
871,
14223,
9646,
5310,
1429,
4193,
12,
2867,
8808,
2416,
5541,
16,
1758,
8808,
394,
5541,
1769,
203,
203,
565,
3885,
1435,
288,
203,
3639,
389,
542,
5541,
24899,
3576,
12021,
10663,
203,
565,
289,
203,
203,
565,
445,
3410,
1435,
1071,
1476,
5024,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
8443,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
5541,
1435,
288,
203,
3639,
2583,
12,
8443,
1435,
422,
389,
3576,
12021,
9334,
315,
902,
326,
3410,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
1654,
8386,
5460,
12565,
1435,
1071,
5024,
1338,
5541,
288,
203,
3639,
389,
542,
5541,
12,
2867,
12,
20,
10019,
203,
565,
289,
203,
203,
565,
445,
7412,
5460,
12565,
12,
2867,
394,
5541,
13,
1071,
5024,
1338,
5541,
288,
203,
3639,
2583,
12,
2704,
5541,
480,
1758,
12,
20,
3631,
315,
7124,
1758,
8863,
203,
3639,
389,
542,
5541,
12,
2704,
5541,
1769,
203,
565,
289,
203,
203,
565,
445,
389,
542,
5541,
12,
2867,
394,
5541,
13,
3238,
288,
203,
3639,
1758,
1592,
5541,
273,
389,
8443,
31,
203,
3639,
389,
8443,
273,
394,
5541,
31,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
12,
1673,
5541,
16,
394,
5541,
1769,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x8aed0055D691e6d619AcC96Ad0fB3461f5774646/sources/contracts/prime-token/PrimeTokenProxy.sol | @notice Prime token contract address @notice Disabled state of the contract through invoke echelon @notice Disabled state of send from | constructor(address _lzEndpoint, address _proxyToken) OFTCore(_lzEndpoint) {
prime = IERC20(_proxyToken);
}
| 3,171,398 | [
1,
23327,
1147,
6835,
1758,
225,
28970,
919,
434,
326,
6835,
3059,
4356,
425,
343,
292,
265,
225,
28970,
919,
434,
1366,
628,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
3885,
12,
2867,
389,
80,
94,
3293,
16,
1758,
389,
5656,
1345,
13,
531,
4464,
4670,
24899,
80,
94,
3293,
13,
288,
203,
3639,
17014,
273,
467,
654,
39,
3462,
24899,
5656,
1345,
1769,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.5.1;
/// @title birthday.sol -- A birthday card for a special person.
/// @author Preston Van Loon <[email protected]>
contract BirthdayCard {
event PassphraseOK(string passphrase);
string public message;
bytes32 hashed_passphrase;
ERC20 constant dai = ERC20(0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359);
/// @dev Initialize the contract
/// @param _message to write inside of the birthday card
/// @param _hashed_passphrase is the keccak256 hashed passphrase
constructor(string memory _message, bytes32 _hashed_passphrase) public {
message = _message;
hashed_passphrase = _hashed_passphrase;
}
/// @dev Withdraw the DAI and selfdestruct this birthday card!
/// Just like real life: take the money out and throw the card away!!
/// @param passphrase is the secret to test.
function withdraw(string memory passphrase) public {
require(isPassphrase(passphrase));
emit PassphraseOK(passphrase);
assert(dai.transfer(msg.sender, dai.balanceOf(address(this))));
selfdestruct(msg.sender);
}
/// @dev How much money is inside of this birthday card?
/// Divide the result of this by 10^18 to get the DAI dollar amount.
function balanceOf() public view returns (uint) {
return dai.balanceOf(address(this));
}
/// @dev Sanity check for the passphrase before sending the transaction.
/// @param passphrase is the secret to test.
function isPassphrase(string memory passphrase) public view returns (bool) {
return keccak256(bytes(passphrase)) == hashed_passphrase;
}
}
/// erc20.sol -- API for the ERC20 token standard
// See <https://github.com/ethereum/EIPs/issues/20>.
contract ERC20Events {
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
}
contract ERC20 is ERC20Events {
function totalSupply() public view returns (uint);
function balanceOf(address guy) public view returns (uint);
function allowance(address src, address guy) public view returns (uint);
function approve(address guy, uint wad) public returns (bool);
function transfer(address dst, uint wad) public returns (bool);
function transferFrom(
address src, address dst, uint wad
) public returns (bool);
} | See <https:github.com/ethereum/EIPs/issues/20>. | contract ERC20Events {
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
}
| 12,767,511 | [
1,
9704,
411,
4528,
30,
6662,
18,
832,
19,
546,
822,
379,
19,
41,
18246,
19,
9618,
19,
3462,
18652,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
4232,
39,
3462,
3783,
288,
203,
565,
871,
1716,
685,
1125,
12,
2867,
8808,
1705,
16,
1758,
8808,
3058,
93,
16,
2254,
341,
361,
1769,
203,
565,
871,
12279,
12,
2867,
8808,
1705,
16,
1758,
8808,
3046,
16,
2254,
341,
361,
1769,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x91C1842E87dE6fCc81b2a83e31Da00345e95059D/sources/contracts/PartyBidRA.sol | Address of a new DAO member and their entry share | event PartyJoined(address indexed member, uint256 value);
| 3,220,137 | [
1,
1887,
434,
279,
394,
463,
20463,
3140,
471,
3675,
1241,
7433,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
871,
6393,
93,
4572,
329,
12,
2867,
8808,
3140,
16,
2254,
5034,
460,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Initializable } from "@openzeppelin/contracts/proxy/Initializable.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import { EnsResolve } from "torn-token/contracts/ENS.sol";
import { ENSNamehash } from "./utils/ENSNamehash.sol";
import { TORN } from "torn-token/contracts/TORN.sol";
import { TornadoStakingRewards } from "./staking/TornadoStakingRewards.sol";
import { IENS } from "./interfaces/IENS.sol";
import "./tornado-proxy/TornadoRouter.sol";
import "./tornado-proxy/FeeManager.sol";
struct RelayerState {
uint256 balance;
bytes32 ensHash;
}
/**
* @notice Registry contract, one of the main contracts of this protocol upgrade.
* The contract should store relayers' addresses and data attributed to the
* master address of the relayer. This data includes the relayers stake and
* his ensHash.
* A relayers master address has a number of subaddresses called "workers",
* these are all addresses which burn stake in communication with the proxy.
* If a relayer is not registered, he is not displayed on the frontend.
* @dev CONTRACT RISKS:
* - if setter functions are compromised, relayer metadata would be at risk, including the noted amount of his balance
* - if burn function is compromised, relayers run the risk of being unable to handle withdrawals
* - the above risk also applies to the nullify balance function
* */
contract RelayerRegistry is Initializable, EnsResolve {
using SafeMath for uint256;
using SafeERC20 for TORN;
using ENSNamehash for bytes;
TORN public immutable torn;
address public immutable governance;
IENS public immutable ens;
TornadoStakingRewards public immutable staking;
FeeManager public immutable feeManager;
address public tornadoRouter;
uint256 public minStakeAmount;
mapping(address => RelayerState) public relayers;
mapping(address => address) public workers;
event RelayerBalanceNullified(address relayer);
event WorkerRegistered(address relayer, address worker);
event WorkerUnregistered(address relayer, address worker);
event StakeAddedToRelayer(address relayer, uint256 amountStakeAdded);
event StakeBurned(address relayer, uint256 amountBurned);
event MinimumStakeAmount(uint256 minStakeAmount);
event RouterRegistered(address tornadoRouter);
event RelayerRegistered(bytes32 relayer, string ensName, address relayerAddress, uint256 stakedAmount);
modifier onlyGovernance() {
require(msg.sender == governance, "only governance");
_;
}
modifier onlyTornadoRouter() {
require(msg.sender == tornadoRouter, "only proxy");
_;
}
modifier onlyRelayer(address sender, address relayer) {
require(workers[sender] == relayer, "only relayer");
_;
}
constructor(
address _torn,
address _governance,
address _ens,
bytes32 _staking,
bytes32 _feeManager
) public {
torn = TORN(_torn);
governance = _governance;
ens = IENS(_ens);
staking = TornadoStakingRewards(resolve(_staking));
feeManager = FeeManager(resolve(_feeManager));
}
/**
* @notice initialize function for upgradeability
* @dev this contract will be deployed behind a proxy and should not assign values at logic address,
* params left out because self explainable
* */
function initialize(bytes32 _tornadoRouter) external initializer {
tornadoRouter = resolve(_tornadoRouter);
}
/**
* @notice This function should register a master address and optionally a set of workeres for a relayer + metadata
* @dev Relayer can't steal other relayers workers since they are registered, and a wallet (msg.sender check) can always unregister itself
* @param ensName ens name of the relayer
* @param stake the initial amount of stake in TORN the relayer is depositing
* */
function register(
string calldata ensName,
uint256 stake,
address[] calldata workersToRegister
) external {
_register(msg.sender, ensName, stake, workersToRegister);
}
/**
* @dev Register function equivalent with permit-approval instead of regular approve.
* */
function registerPermit(
string calldata ensName,
uint256 stake,
address[] calldata workersToRegister,
address relayer,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
torn.permit(relayer, address(this), stake, deadline, v, r, s);
_register(relayer, ensName, stake, workersToRegister);
}
function _register(
address relayer,
string calldata ensName,
uint256 stake,
address[] calldata workersToRegister
) internal {
bytes32 ensHash = bytes(ensName).namehash();
require(relayer == ens.owner(ensHash), "only ens owner");
require(workers[relayer] == address(0), "cant register again");
RelayerState storage metadata = relayers[relayer];
require(metadata.ensHash == bytes32(0), "registered already");
require(stake >= minStakeAmount, "!min_stake");
torn.safeTransferFrom(relayer, address(staking), stake);
emit StakeAddedToRelayer(relayer, stake);
metadata.balance = stake;
metadata.ensHash = ensHash;
workers[relayer] = relayer;
for (uint256 i = 0; i < workersToRegister.length; i++) {
address worker = workersToRegister[i];
_registerWorker(relayer, worker);
}
emit RelayerRegistered(ensHash, ensName, relayer, stake);
}
/**
* @notice This function should allow relayers to register more workeres
* @param relayer Relayer which should send message from any worker which is already registered
* @param worker Address to register
* */
function registerWorker(address relayer, address worker) external onlyRelayer(msg.sender, relayer) {
_registerWorker(relayer, worker);
}
function _registerWorker(address relayer, address worker) internal {
require(workers[worker] == address(0), "can't steal an address");
workers[worker] = relayer;
emit WorkerRegistered(relayer, worker);
}
/**
* @notice This function should allow anybody to unregister an address they own
* @dev designed this way as to allow someone to unregister themselves in case a relayer misbehaves
* - this should be followed by an action like burning relayer stake
* - there was an option of allowing the sender to burn relayer stake in case of malicious behaviour, this feature was not included in the end
* - reverts if trying to unregister master, otherwise contract would break. in general, there should be no reason to unregister master at all
* */
function unregisterWorker(address worker) external {
if (worker != msg.sender) require(workers[worker] == msg.sender, "only owner of worker");
require(workers[worker] != worker, "cant unregister master");
emit WorkerUnregistered(workers[worker], worker);
workers[worker] = address(0);
}
/**
* @notice This function should allow anybody to stake to a relayer more TORN
* @param relayer Relayer main address to stake to
* @param stake Stake to be added to relayer
* */
function stakeToRelayer(address relayer, uint256 stake) external {
_stakeToRelayer(msg.sender, relayer, stake);
}
/**
* @dev stakeToRelayer function equivalent with permit-approval instead of regular approve.
* @param staker address from that stake is paid
* */
function stakeToRelayerPermit(
address relayer,
uint256 stake,
address staker,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
torn.permit(staker, address(this), stake, deadline, v, r, s);
_stakeToRelayer(staker, relayer, stake);
}
function _stakeToRelayer(
address staker,
address relayer,
uint256 stake
) internal {
require(workers[relayer] == relayer, "!registered");
torn.safeTransferFrom(staker, address(staking), stake);
relayers[relayer].balance = stake.add(relayers[relayer].balance);
emit StakeAddedToRelayer(relayer, stake);
}
/**
* @notice This function should burn some relayer stake on withdraw and notify staking of this
* @dev IMPORTANT FUNCTION:
* - This should be only called by the tornado proxy
* - Should revert if relayer does not call proxy from valid worker
* - Should not overflow
* - Should underflow and revert (SafeMath) on not enough stake (balance)
* @param sender worker to check sender == relayer
* @param relayer address of relayer who's stake is being burned
* @param pool instance to get fee for
* */
function burn(
address sender,
address relayer,
ITornadoInstance pool
) external onlyTornadoRouter {
address masterAddress = workers[sender];
if (masterAddress == address(0)) {
require(workers[relayer] == address(0), "Only custom relayer");
return;
}
require(masterAddress == relayer, "only relayer");
uint256 toBurn = feeManager.instanceFeeWithUpdate(pool);
relayers[relayer].balance = relayers[relayer].balance.sub(toBurn);
staking.addBurnRewards(toBurn);
emit StakeBurned(relayer, toBurn);
}
/**
* @notice This function should allow governance to set the minimum stake amount
* @param minAmount new minimum stake amount
* */
function setMinStakeAmount(uint256 minAmount) external onlyGovernance {
minStakeAmount = minAmount;
emit MinimumStakeAmount(minAmount);
}
/**
* @notice This function should allow governance to set a new tornado proxy address
* @param tornadoRouterAddress address of the new proxy
* */
function setTornadoRouter(address tornadoRouterAddress) external onlyGovernance {
tornadoRouter = tornadoRouterAddress;
emit RouterRegistered(tornadoRouterAddress);
}
/**
* @notice This function should allow governance to nullify a relayers balance
* @dev IMPORTANT FUNCTION:
* - Should nullify the balance
* - Adding nullified balance as rewards was refactored to allow for the flexibility of these funds (for gov to operate with them)
* @param relayer address of relayer who's balance is to nullify
* */
function nullifyBalance(address relayer) external onlyGovernance {
address masterAddress = workers[relayer];
require(relayer == masterAddress, "must be master");
relayers[masterAddress].balance = 0;
emit RelayerBalanceNullified(relayer);
}
/**
* @notice This function should check if a worker is associated with a relayer
* @param toResolve address to check
* @return true if is associated
* */
function isRelayer(address toResolve) external view returns (bool) {
return workers[toResolve] != address(0);
}
/**
* @notice This function should check if a worker is registered to the relayer stated
* @param relayer relayer to check
* @param toResolve address to check
* @return true if registered
* */
function isRelayerRegistered(address relayer, address toResolve) external view returns (bool) {
return workers[toResolve] == relayer;
}
/**
* @notice This function should get a relayers ensHash
* @param relayer address to fetch for
* @return relayer's ensHash
* */
function getRelayerEnsHash(address relayer) external view returns (bytes32) {
return relayers[workers[relayer]].ensHash;
}
/**
* @notice This function should get a relayers balance
* @param relayer relayer who's balance is to fetch
* @return relayer's balance
* */
function getRelayerBalance(address relayer) external view returns (uint256) {
return relayers[workers[relayer]].balance;
}
}
| * @notice This function should allow governance to set the minimum stake amount @param minAmount new minimum stake amount / | function setMinStakeAmount(uint256 minAmount) external onlyGovernance {
minStakeAmount = minAmount;
emit MinimumStakeAmount(minAmount);
}
| 2,561,609 | [
1,
2503,
445,
1410,
1699,
314,
1643,
82,
1359,
358,
444,
326,
5224,
384,
911,
3844,
225,
1131,
6275,
394,
5224,
384,
911,
3844,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
27724,
510,
911,
6275,
12,
11890,
5034,
1131,
6275,
13,
3903,
1338,
43,
1643,
82,
1359,
288,
203,
565,
1131,
510,
911,
6275,
273,
1131,
6275,
31,
203,
565,
3626,
23456,
510,
911,
6275,
12,
1154,
6275,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.10;contract CVP { // set contract name to token name
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
// Balances for each account
mapping(address => uint256) balances;address devAddress;// Events
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Transfer(address indexed from, address indexed to, uint256 value);
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint256)) allowed;// This is the constructor and automatically runs when the smart contract is uploaded
function CVP() { // Set the constructor to the same name as the contract name
name = "Cross Crowd Value Platform"; // set the token name here
symbol = "CVP"; // set the Symbol here
decimals = 6; // set the number of decimals
devAddress=0x7bE4dD13A34A65f25A447eC2F812fd94Aa74ccdB; // Add the address that you will distribute tokens from here
uint initialBalance=1000000*20000000000; // 1M tokens
balances[devAddress]=initialBalance;
totalSupply+=initialBalance; // Set the total suppy
}function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}// Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _amount) returns (bool success) {
if (balances[msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}function transferFrom(
address _from,
address _to,
uint256 _amount
) returns (bool success) {
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
return true;
} else {
return false;
}
}// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _amount) returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
} | Add the address that you will distribute tokens from here
| devAddress=0x7bE4dD13A34A65f25A447eC2F812fd94Aa74ccdB; | 13,108,296 | [
1,
986,
326,
1758,
716,
1846,
903,
25722,
2430,
628,
2674,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
4461,
1887,
33,
20,
92,
27,
70,
41,
24,
72,
40,
3437,
37,
5026,
37,
9222,
74,
2947,
37,
6334,
27,
73,
39,
22,
42,
28,
2138,
8313,
11290,
37,
69,
5608,
952,
72,
38,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/*
* Semaphore - Zero-knowledge signaling on Ethereum
* Copyright (C) 2020 Barry WhiteHat <[email protected]>, Kobi
* Gurkan <[email protected]> and Koh Wei Jie ([email protected])
*
* This file is part of Semaphore.
*
* Semaphore is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Semaphore is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Semaphore. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.0;
import "./verifier.sol";
import { IncrementalMerkleTree } from "./IncrementalMerkleTree.sol";
import "./Ownable.sol";
contract Semaphore is Verifier, IncrementalMerkleTree, Ownable {
// The external nullifier helps to prevent double-signalling by the same
// user. An external nullifier can be active or deactivated.
// Each node in the linked list
struct ExternalNullifierNode {
uint232 next;
bool exists;
bool isActive;
}
// We store the external nullifiers using a mapping of the form:
// enA => { next external nullifier; if enA exists; if enA is active }
// Think of it as a linked list.
mapping (uint232 => ExternalNullifierNode) public
externalNullifierLinkedList;
uint256 public numExternalNullifiers = 0;
// First and last external nullifiers for linked list enumeration
uint232 public firstExternalNullifier = 0;
uint232 public lastExternalNullifier = 0;
// Whether broadcastSignal() can only be called by the owner of this
// contract. This is the case as a safe default.
bool public isBroadcastPermissioned = true;
// Whether the contract has already seen a particular nullifier hash
mapping (uint256 => bool) public nullifierHashHistory;
event PermissionSet(bool indexed newPermission);
event ExternalNullifierAdd(uint232 indexed externalNullifier);
event ExternalNullifierChangeStatus(
uint232 indexed externalNullifier,
bool indexed active
);
// This value should be equal to
// 0x7d10c03d1f7884c85edee6353bd2b2ffbae9221236edde3778eac58089912bc0
// which you can calculate using the following ethersjs code:
// ethers.utils.solidityKeccak256(['bytes'], [ethers.utils.toUtf8Bytes('Semaphore')])
// By setting the value of unset (empty) tree leaves to this
// nothing-up-my-sleeve value, the authors hope to demonstrate that they do
// not have its preimage and therefore cannot spend funds they do not own.
uint256 public NOTHING_UP_MY_SLEEVE_ZERO =
uint256(keccak256(abi.encodePacked('Semaphore'))) % SNARK_SCALAR_FIELD;
/*
* If broadcastSignal is permissioned, check if msg.sender is the contract
* owner
*/
modifier onlyOwnerIfPermissioned() {
require(
!isBroadcastPermissioned || isOwner(),
"Semaphore: broadcast permission denied"
);
_;
}
/*
* @param _treeLevels The depth of the identity tree.
* @param _firstExternalNullifier The first identity nullifier to add.
*/
constructor(uint8 _treeLevels, uint232 _firstExternalNullifier)
IncrementalMerkleTree(_treeLevels, NOTHING_UP_MY_SLEEVE_ZERO)
Ownable()
public {
addEn(_firstExternalNullifier, true);
}
/*
* Registers a new user.
* @param _identity_commitment The user's identity commitment, which is the
* hash of their public key and their identity
* nullifier (a random 31-byte value). It should
* be the output of a Pedersen hash. It is the
* responsibility of the caller to verify this.
*/
function insertIdentity(uint256 _identityCommitment) public onlyOwner
returns (uint256) {
// Ensure that the given identity commitment is not the zero value
require(
_identityCommitment != NOTHING_UP_MY_SLEEVE_ZERO,
"Semaphore: identity commitment cannot be the nothing-up-my-sleeve-value"
);
return insertLeaf(_identityCommitment);
}
/*
* Checks if all values within pi_a, pi_b, and pi_c of a zk-SNARK are less
* than the scalar field.
* @param _a The corresponding `a` parameter to verifier.sol's
* verifyProof()
* @param _b The corresponding `b` parameter to verifier.sol's
* verifyProof()
* @param _c The corresponding `c` parameter to verifier.sol's
verifyProof()
*/
function areAllValidFieldElements(
uint256[8] memory _proof
) internal pure returns (bool) {
return
_proof[0] < SNARK_SCALAR_FIELD &&
_proof[1] < SNARK_SCALAR_FIELD &&
_proof[2] < SNARK_SCALAR_FIELD &&
_proof[3] < SNARK_SCALAR_FIELD &&
_proof[4] < SNARK_SCALAR_FIELD &&
_proof[5] < SNARK_SCALAR_FIELD &&
_proof[6] < SNARK_SCALAR_FIELD &&
_proof[7] < SNARK_SCALAR_FIELD;
}
/*
* Produces a keccak256 hash of the given signal, shifted right by 8 bits.
* @param _signal The signal to hash
*/
function hashSignal(bytes memory _signal) internal pure returns (uint256) {
return uint256(keccak256(_signal)) >> 8;
}
/*
* A convenience function which returns a uint256 array of 8 elements which
* comprise a Groth16 zk-SNARK proof's pi_a, pi_b, and pi_c values.
* @param _a The corresponding `a` parameter to verifier.sol's
* verifyProof()
* @param _b The corresponding `b` parameter to verifier.sol's
* verifyProof()
* @param _c The corresponding `c` parameter to verifier.sol's
* verifyProof()
*/
function packProof (
uint256[2] memory _a,
uint256[2][2] memory _b,
uint256[2] memory _c
) public pure returns (uint256[8] memory) {
return [
_a[0],
_a[1],
_b[0][0],
_b[0][1],
_b[1][0],
_b[1][1],
_c[0],
_c[1]
];
}
/*
* A convenience function which converts an array of 8 elements, generated
* by packProof(), into a format which verifier.sol's verifyProof()
* accepts.
* @param _proof The proof elements.
*/
function unpackProof(
uint256[8] memory _proof
) public pure returns (
uint256[2] memory,
uint256[2][2] memory,
uint256[2] memory
) {
return (
[_proof[0], _proof[1]],
[
[_proof[2], _proof[3]],
[_proof[4], _proof[5]]
],
[_proof[6], _proof[7]]
);
}
/*
* A convenience view function which helps operators to easily verify all
* inputs to broadcastSignal() using a single contract call. This helps
* them to save gas by detecting invalid inputs before they invoke
* broadcastSignal(). Note that this function does the same checks as
* `isValidSignalAndProof` but returns a bool instead of using require()
* statements.
* @param _signal The signal to broadcast
* @param _proof The proof elements.
* @param _root The Merkle tree root
* @param _nullifiersHash The nullifiers hash
* @param _signalHash The signal hash. This is included so as to verify in
* Solidity that the signal hash computed off-chain
* matches.
* @param _externalNullifier The external nullifier
*/
function preBroadcastCheck (
bytes memory _signal,
uint256[8] memory _proof,
uint256 _root,
uint256 _nullifiersHash,
uint256 _signalHash,
uint232 _externalNullifier
) public view returns (bool) {
uint256[4] memory publicSignals =
[_root, _nullifiersHash, _signalHash, _externalNullifier];
(uint256[2] memory a, uint256[2][2] memory b, uint256[2] memory c) =
unpackProof(_proof);
return nullifierHashHistory[_nullifiersHash] == false &&
hashSignal(_signal) == _signalHash &&
_signalHash == hashSignal(_signal) &&
isExternalNullifierActive(_externalNullifier) &&
rootHistory[_root] &&
areAllValidFieldElements(_proof) &&
_root < SNARK_SCALAR_FIELD &&
_nullifiersHash < SNARK_SCALAR_FIELD &&
verifyProof(a, b, c, publicSignals);
}
/*
* A modifier which ensures that the signal and proof are valid.
* @param _signal The signal to broadcast
* @param _proof The proof elements.
* @param _root The Merkle tree root
* @param _nullifiersHash The nullifiers hash
* @param _signalHash The signal hash
* @param _externalNullifier The external nullifier
*/
modifier isValidSignalAndProof (
bytes memory _signal,
uint256[8] memory _proof,
uint256 _root,
uint256 _nullifiersHash,
uint232 _externalNullifier
) {
// Check whether each element in _proof is a valid field element. Even
// if verifier.sol does this check too, it is good to do so here for
// the sake of good protocol design.
require(
areAllValidFieldElements(_proof),
"Semaphore: invalid field element(s) in proof"
);
// Check whether the nullifier hash has been seen
require(
nullifierHashHistory[_nullifiersHash] == false,
"Semaphore: nullifier already seen"
);
// Check whether the nullifier hash is active
require(
isExternalNullifierActive(_externalNullifier),
"Semaphore: external nullifier not found"
);
// Check whether the given Merkle root has been seen previously
require(rootHistory[_root], "Semaphore: root not seen");
uint256 signalHash = hashSignal(_signal);
// Check whether _nullifiersHash is a valid field element.
require(
_nullifiersHash < SNARK_SCALAR_FIELD,
"Semaphore: the nullifiers hash must be lt the snark scalar field"
);
uint256[4] memory publicSignals =
[_root, _nullifiersHash, signalHash, _externalNullifier];
(uint256[2] memory a, uint256[2][2] memory b, uint256[2] memory c) =
unpackProof(_proof);
require(
verifyProof(a, b, c, publicSignals),
"Semaphore: invalid proof"
);
// Note that we don't need to check if signalHash is less than
// SNARK_SCALAR_FIELD because it always holds true due to the
// definition of hashSignal()
_;
}
/*
* Broadcasts the signal.
* @param _signal The signal to broadcast
* @param _proof The proof elements.
* @param _root The root of the Merkle tree (the 1st public signal)
* @param _nullifiersHash The nullifiers hash (the 2nd public signal)
* @param _externalNullifier The nullifiers hash (the 4th public signal)
*/
function broadcastSignal(
bytes memory _signal,
uint256[8] memory _proof,
uint256 _root,
uint256 _nullifiersHash,
uint232 _externalNullifier
) public
onlyOwnerIfPermissioned
isValidSignalAndProof(
_signal, _proof, _root, _nullifiersHash, _externalNullifier
)
{
// Client contracts should be responsible for storing the signal and/or
// emitting it as an event
// Store the nullifiers hash to prevent double-signalling
nullifierHashHistory[_nullifiersHash] = true;
}
/*
* A private helper function which adds an external nullifier.
* @param _externalNullifier The external nullifier to add.
* @param _isFirst Whether _externalNullifier is the first external
* nullifier. Only the constructor should set _isFirst to true when it
* calls addEn().
*/
function addEn(uint232 _externalNullifier, bool isFirst) private {
if (isFirst) {
firstExternalNullifier = _externalNullifier;
} else {
// The external nullifier must not have already been set
require(
externalNullifierLinkedList[_externalNullifier].exists == false,
"Semaphore: external nullifier already set"
);
// Connect the previously added external nullifier node to this one
externalNullifierLinkedList[lastExternalNullifier].next =
_externalNullifier;
}
// Add a new external nullifier
externalNullifierLinkedList[_externalNullifier].next = 0;
externalNullifierLinkedList[_externalNullifier].isActive = true;
externalNullifierLinkedList[_externalNullifier].exists = true;
// Set the last external nullifier to this one
lastExternalNullifier = _externalNullifier;
numExternalNullifiers ++;
emit ExternalNullifierAdd(_externalNullifier);
}
/*
* Adds an external nullifier to the contract. This external nullifier is
* active once it is added. Only the owner can do this.
* @param _externalNullifier The new external nullifier to set.
*/
function addExternalNullifier(uint232 _externalNullifier) public
onlyOwner {
addEn(_externalNullifier, false);
}
/*
* Deactivate an external nullifier. The external nullifier must already be
* active for this function to work. Only the owner can do this.
* @param _externalNullifier The new external nullifier to deactivate.
*/
function deactivateExternalNullifier(uint232 _externalNullifier) public
onlyOwner {
// The external nullifier must already exist
require(
externalNullifierLinkedList[_externalNullifier].exists,
"Semaphore: external nullifier not found"
);
// The external nullifier must already be active
require(
externalNullifierLinkedList[_externalNullifier].isActive == true,
"Semaphore: external nullifier already deactivated"
);
// Deactivate the external nullifier. Note that we don't change the
// value of nextEn.
externalNullifierLinkedList[_externalNullifier].isActive = false;
emit ExternalNullifierChangeStatus(_externalNullifier, false);
}
/*
* Reactivate an external nullifier. The external nullifier must already be
* inactive for this function to work. Only the owner can do this.
* @param _externalNullifier The new external nullifier to reactivate.
*/
function reactivateExternalNullifier(uint232 _externalNullifier) public
onlyOwner {
// The external nullifier must already exist
require(
externalNullifierLinkedList[_externalNullifier].exists,
"Semaphore: external nullifier not found"
);
// The external nullifier must already have been deactivated
require(
externalNullifierLinkedList[_externalNullifier].isActive == false,
"Semaphore: external nullifier is already active"
);
// Reactivate the external nullifier
externalNullifierLinkedList[_externalNullifier].isActive = true;
emit ExternalNullifierChangeStatus(_externalNullifier, true);
}
/*
* Returns true if and only if the specified external nullifier is active
* @param _externalNullifier The specified external nullifier.
*/
function isExternalNullifierActive(uint232 _externalNullifier) public view
returns (bool) {
return externalNullifierLinkedList[_externalNullifier].isActive;
}
/*
* Returns the next external nullifier after the specified external
* nullifier in the linked list.
* @param _externalNullifier The specified external nullifier.
*/
function getNextExternalNullifier(uint232 _externalNullifier) public view
returns (uint232) {
require(
externalNullifierLinkedList[_externalNullifier].exists,
"Semaphore: no such external nullifier"
);
uint232 n = externalNullifierLinkedList[_externalNullifier].next;
require(
numExternalNullifiers > 1 && externalNullifierLinkedList[n].exists,
"Semaphore: no external nullifier exists after the specified one"
);
return n;
}
/*
* Returns the number of inserted identity commitments.
*/
function getNumIdentityCommitments() public view returns (uint256) {
return nextLeafIndex;
}
/*
* Sets the `isBroadcastPermissioned` storage variable, which determines
* whether broadcastSignal can or cannot be called by only the contract
* owner.
* @param _newPermission True if the broadcastSignal can only be called by
* the contract owner; and False otherwise.
*/
function setPermissioning(bool _newPermission) public onlyOwner {
isBroadcastPermissioned = _newPermission;
emit PermissionSet(_newPermission);
}
}
| A convenience function which returns a uint256 array of 8 elements which comprise a Groth16 zk-SNARK proof's pi_a, pi_b, and pi_c values. @param _a The corresponding `a` parameter to verifier.sol's verifyProof() @param _b The corresponding `b` parameter to verifier.sol's verifyProof() @param _c The corresponding `c` parameter to verifier.sol's verifyProof()/ | function packProof (
uint256[2] memory _a,
uint256[2][2] memory _b,
uint256[2] memory _c
) public pure returns (uint256[8] memory) {
return [
_a[0],
_a[1],
_b[0][0],
_b[0][1],
_b[1][0],
_b[1][1],
_c[0],
_c[1]
];
}
| 7,232,873 | [
1,
37,
13553,
445,
1492,
1135,
279,
2254,
5034,
526,
434,
1725,
2186,
1492,
532,
12113,
279,
611,
303,
451,
2313,
14164,
17,
13653,
9584,
14601,
1807,
4790,
67,
69,
16,
4790,
67,
70,
16,
471,
4790,
67,
71,
225,
924,
18,
225,
389,
69,
1021,
4656,
1375,
69,
68,
1569,
358,
20130,
18,
18281,
1807,
6647,
3929,
20439,
1435,
225,
389,
70,
1021,
4656,
1375,
70,
68,
1569,
358,
20130,
18,
18281,
1807,
6647,
3929,
20439,
1435,
225,
389,
71,
1021,
4656,
1375,
71,
68,
1569,
358,
20130,
18,
18281,
1807,
6647,
3929,
20439,
1435,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
2298,
20439,
261,
203,
3639,
2254,
5034,
63,
22,
65,
3778,
389,
69,
16,
203,
3639,
2254,
5034,
63,
22,
6362,
22,
65,
3778,
389,
70,
16,
203,
3639,
2254,
5034,
63,
22,
65,
3778,
389,
71,
203,
565,
262,
1071,
16618,
1135,
261,
11890,
5034,
63,
28,
65,
3778,
13,
288,
203,
203,
3639,
327,
306,
203,
5411,
389,
69,
63,
20,
6487,
203,
5411,
389,
69,
63,
21,
6487,
7010,
5411,
389,
70,
63,
20,
6362,
20,
6487,
203,
5411,
389,
70,
63,
20,
6362,
21,
6487,
203,
5411,
389,
70,
63,
21,
6362,
20,
6487,
203,
5411,
389,
70,
63,
21,
6362,
21,
6487,
203,
5411,
389,
71,
63,
20,
6487,
203,
5411,
389,
71,
63,
21,
65,
203,
3639,
308,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xdDc2c27eA8a42b35B329c4e0216600F12EED13d1/sources/contracts/wombat-core/pool/CrossChainPool.sol | Check it doesn't exceed maximum in-coming credits | function _doSwapCreditForTokens(
address toToken,
uint256 fromCreditAmount,
uint256 minimumToAmount,
address receiver
) internal returns (uint256 actualToAmount, uint256 toTokenFee) {
if (fromCreditAmount == 0) revert WOMBAT_ZERO_CREDIT_AMOUNT();
IAsset toAsset = _assetOf(toToken);
uint8 toDecimal = toAsset.underlyingTokenDecimals();
(actualToAmount, toTokenFee) = _swapCreditForTokens(
toAsset,
fromCreditAmount,
minimumToAmount.toWad(toDecimal)
);
actualToAmount = actualToAmount.fromWad(toDecimal);
toTokenFee = toTokenFee.fromWad(toDecimal);
toAsset.transferUnderlyingToken(receiver, actualToAmount);
totalCreditBurned += _to128(fromCreditAmount);
if (totalCreditBurned > maximumInboundCredit + totalCreditMinted) revert POOL__REACH_MAXIMUM_BURNED_CREDIT();
emit SwapCreditForTokens(fromCreditAmount, toToken, actualToAmount, toTokenFee, receiver);
}
| 2,762,484 | [
1,
1564,
518,
3302,
1404,
9943,
4207,
316,
17,
5522,
6197,
1282,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
2896,
12521,
16520,
1290,
5157,
12,
203,
3639,
1758,
358,
1345,
16,
203,
3639,
2254,
5034,
628,
16520,
6275,
16,
203,
3639,
2254,
5034,
5224,
774,
6275,
16,
203,
3639,
1758,
5971,
203,
565,
262,
2713,
1135,
261,
11890,
5034,
3214,
774,
6275,
16,
2254,
5034,
358,
1345,
14667,
13,
288,
203,
3639,
309,
261,
2080,
16520,
6275,
422,
374,
13,
15226,
678,
1872,
38,
789,
67,
24968,
67,
5458,
40,
1285,
67,
2192,
51,
5321,
5621,
203,
203,
3639,
467,
6672,
358,
6672,
273,
389,
9406,
951,
12,
869,
1345,
1769,
203,
3639,
2254,
28,
358,
5749,
273,
358,
6672,
18,
9341,
6291,
1345,
31809,
5621,
203,
3639,
261,
18672,
774,
6275,
16,
358,
1345,
14667,
13,
273,
389,
22270,
16520,
1290,
5157,
12,
203,
5411,
358,
6672,
16,
203,
5411,
628,
16520,
6275,
16,
203,
5411,
5224,
774,
6275,
18,
869,
59,
361,
12,
869,
5749,
13,
203,
3639,
11272,
203,
3639,
3214,
774,
6275,
273,
3214,
774,
6275,
18,
2080,
59,
361,
12,
869,
5749,
1769,
203,
3639,
358,
1345,
14667,
273,
358,
1345,
14667,
18,
2080,
59,
361,
12,
869,
5749,
1769,
203,
203,
3639,
358,
6672,
18,
13866,
14655,
6291,
1345,
12,
24454,
16,
3214,
774,
6275,
1769,
203,
3639,
2078,
16520,
38,
321,
329,
1011,
389,
869,
10392,
12,
2080,
16520,
6275,
1769,
203,
203,
3639,
309,
261,
4963,
16520,
38,
321,
329,
405,
4207,
20571,
16520,
397,
2078,
16520,
49,
474,
329,
13,
15226,
13803,
1741,
972,
862,
18133,
67,
6694,
18605,
67,
38,
2
]
|
/**
*Submitted for verification at Etherscan.io on 2021-11-14
*/
// SPDX-License-Identifier: MIT
// File: contracts/SafeMath.sol
pragma solidity ^0.8.1;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
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)
{
unchecked {
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)
{
unchecked {
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)
{
unchecked {
// 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)
{
unchecked {
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)
{
unchecked {
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) {
return a + b;
}
/**
* @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 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) {
return a * b;
}
/**
* @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.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
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) {
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) {
unchecked {
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.
*
* 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) {
unchecked {
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) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: contracts/Strings.sol
pragma solidity ^0.8.1;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length)
internal
pure
returns (string memory)
{
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: contracts/Context.sol
pragma solidity ^0.8.1;
/**
* @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: contracts/Ownable.sol
pragma solidity ^0.8.1;
/**
* @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/Address.sol
pragma solidity ^0.8.1;
/**
* @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: contracts/IERC721Receiver.sol
pragma solidity ^0.8.1;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: contracts/IERC165.sol
pragma solidity ^0.8.1;
/**
* @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.sol
pragma solidity ^0.8.1;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return interfaceId == type(IERC165).interfaceId;
}
}
// File: contracts/IERC721.sol
pragma solidity ^0.8.1;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId)
external
view
returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: contracts/IERC721Enumerable.sol
pragma solidity ^0.8.1;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
external
view
returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: contracts/IERC721Metadata.sol
pragma solidity ^0.8.1;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: contracts/ERC721.sol
pragma solidity ^0.8.1;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner)
public
view
virtual
override
returns (uint256)
{
require(
owner != address(0),
"ERC721: balance query for the zero address"
);
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
address owner = _owners[tokenId];
require(
owner != address(0),
"ERC721: owner query for nonexistent token"
);
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory 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 = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
virtual
override
returns (address)
{
require(
_exists(tokenId),
"ERC721: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
virtual
returns (bool)
{
require(
_exists(tokenId),
"ERC721: operator query for nonexistent token"
);
address owner = ERC721.ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(
ERC721.ownerOf(tokenId) == from,
"ERC721: transfer of token that is not own"
);
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
return retval == IERC721Receiver.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 {}
}
// File: contracts/ERC721Enumerable.sol
pragma solidity ^0.8.1;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(IERC165, ERC721)
returns (bool)
{
return
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256)
{
require(
index < ERC721.balanceOf(owner),
"ERC721Enumerable: owner index out of bounds"
);
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
virtual
override
returns (uint256)
{
require(
index < ERC721Enumerable.totalSupply(),
"ERC721Enumerable: global index out of bounds"
);
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId)
private
{
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: contracts/TheCubeNFT.sol
pragma solidity >=0.8.0 <0.9.0;
interface CopycatInterface {
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256 balance);
}
/**
* @title TheCubeNFT
*/
contract TheCubeNFT is ERC721Enumerable, Ownable {
using SafeMath for uint256;
string public baseTokenURI = "";
string public notRevealedURI = "";
string public baseExtension = ".json";
uint256 public maxSupply = 256; // 2^8
uint256 public cubeCost = 0.0496 ether; // 2^8(1/2^0+1/2^1+1/2^2+1/2^3+1/2^4)/10^(2^2)
uint256 public cubeSpecialCost = 0.0384 ether; // 2^8(1/2^0+1/2^1)/10^(2^2)
uint256 public totalMint = 0;
uint8 public maxPerWallet = 4; // 2^8(1/2^0+1/2^1+1/2^4)/10^2
bool public revealed = false;
mapping(address => uint8) public minted;
address public copycatAddress = 0x2f1bd435E2b928C1744202daE9400D10A2D569dC;
CopycatInterface CopycatContract = CopycatInterface(copycatAddress);
constructor(
string memory _name,
string memory _symbol,
string memory _uri,
string memory _notRevealedURI
) ERC721(_name, _symbol) {
baseTokenURI = _uri;
notRevealedURI = _notRevealedURI;
mint(8);
}
/**
* @dev Mint _num of Cubes for COPYCAT holders (4 max per wallet)
* @param _numOfCubes Quantity to mint
*/
function mintForCOPYCAT(uint8 _numOfCubes) public payable {
require(
totalMint + uint256(_numOfCubes) <= maxSupply,
"Sorry, all Cubes have been sold."
);
require(
CopycatContract.balanceOf(msg.sender) >= 1, "You need to have at least 1 COPYCAT!"
);
require(
_numOfCubes + minted[msg.sender] <= maxPerWallet,
"Max 4 per wallet!"
);
require(
msg.value >= uint256(_numOfCubes) * cubeSpecialCost,
"Not enough ETH..."
);
require(
tx.origin == msg.sender,
"Cannot mint through a custom contract!"
); // just in case
for (uint8 i = 0; i < _numOfCubes; i++) {
_safeMint(msg.sender, ++totalMint);
}
minted[msg.sender] += _numOfCubes;
}
/**
* @dev Mint _num of Cubes (4 max per wallet)
* @param _numOfCubes Quantity to mint
*/
function mint(uint8 _numOfCubes) public payable {
require(
totalMint + uint256(_numOfCubes) <= maxSupply,
"Sorry, all Cubes have been sold."
);
if (msg.sender != owner()) {
require(
_numOfCubes + minted[msg.sender] <= maxPerWallet,
"Max 4 per wallet!"
);
require(
msg.value >= uint256(_numOfCubes) * cubeCost,
"Not enough ETH..."
);
}
require(
tx.origin == msg.sender,
"Cannot mint through a custom contract!"
); // just in case
for (uint8 i = 0; i < _numOfCubes; i++) {
_safeMint(msg.sender, ++totalMint);
}
minted[msg.sender] += _numOfCubes;
}
/**
* @dev get the ids of the Cube owned by _owner
* @param _owner address
*/
function walletOfOwner(address _owner)
external
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
/**
* @dev set revealed to true
*/
function reveal() external onlyOwner {
revealed = true;
}
/**
* @dev change the notRevealedURI
* @param _notRevealedURI Not revealed URI
*/
function setNotRevealedURI(string memory _notRevealedURI)
external
onlyOwner
{
notRevealedURI = _notRevealedURI;
}
/**
* @dev change the baseTokenURI
* @param _baseTokenURI base token URI
*/
function setBaseURI(string memory _baseTokenURI) external onlyOwner {
baseTokenURI = _baseTokenURI;
}
/**
* @dev change the cost (just in case)
* @param _cost new cost in wei
*/
function setCost(uint256 _cost) external onlyOwner {
cubeCost = _cost;
}
/**
* @dev change the special cost (just in case)
* @param _specialCost new special cost in wei
*/
function setSpecialCost(uint256 _specialCost) external onlyOwner {
cubeSpecialCost = _specialCost;
}
/**
* @dev change the max amount per wallet
* @param _maxPerWallet max per wallet
*/
function setMaxPerWallet(uint8 _maxPerWallet) public onlyOwner {
maxPerWallet = _maxPerWallet;
}
/**
* @dev returns the token URI of _tokenId
* @param _tokenId id of the token
*/
function tokenURI(uint256 _tokenId)
public
view
override
returns (string memory)
{
require(_exists(_tokenId), "This cube doesn't exist!");
if (revealed == false) {
return notRevealedURI;
}
return
string(
abi.encodePacked(
baseTokenURI,
Strings.toString(_tokenId),
baseExtension
)
);
}
/**
* @dev withdraw all balance of this contract
*/
function withdraw() external payable onlyOwner {
(bool success, ) = payable(msg.sender).call{
value: address(this).balance
}("");
require(success, "Withdraw failed...");
}
/**
* @dev set the base extension of the metadata file (only Owner)
* @param _newBaseExtension extension (empty or with a dot in front)
*/
function setBaseExtension(string memory _newBaseExtension)
public
onlyOwner
{
baseExtension = _newBaseExtension;
}
} | * @dev Mint _num of Cubes for COPYCAT holders (4 max per wallet) @param _numOfCubes Quantity to mint/ | function mintForCOPYCAT(uint8 _numOfCubes) public payable {
require(
totalMint + uint256(_numOfCubes) <= maxSupply,
"Sorry, all Cubes have been sold."
);
require(
CopycatContract.balanceOf(msg.sender) >= 1, "You need to have at least 1 COPYCAT!"
);
require(
_numOfCubes + minted[msg.sender] <= maxPerWallet,
"Max 4 per wallet!"
);
require(
msg.value >= uint256(_numOfCubes) * cubeSpecialCost,
"Not enough ETH..."
);
require(
tx.origin == msg.sender,
"Cannot mint through a custom contract!"
for (uint8 i = 0; i < _numOfCubes; i++) {
_safeMint(msg.sender, ++totalMint);
}
minted[msg.sender] += _numOfCubes;
}
| 6,672,911 | [
1,
49,
474,
389,
2107,
434,
385,
23317,
364,
27776,
14130,
366,
4665,
261,
24,
943,
1534,
9230,
13,
225,
389,
2107,
951,
39,
23317,
18189,
358,
312,
474,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
312,
474,
1290,
24875,
14130,
12,
11890,
28,
389,
2107,
951,
39,
23317,
13,
1071,
8843,
429,
288,
203,
3639,
2583,
12,
203,
5411,
2078,
49,
474,
397,
2254,
5034,
24899,
2107,
951,
39,
23317,
13,
1648,
943,
3088,
1283,
16,
203,
5411,
315,
28898,
16,
777,
385,
23317,
1240,
2118,
272,
1673,
1199,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
5631,
2574,
8924,
18,
12296,
951,
12,
3576,
18,
15330,
13,
1545,
404,
16,
315,
6225,
1608,
358,
1240,
622,
4520,
404,
27776,
14130,
4442,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
389,
2107,
951,
39,
23317,
397,
312,
474,
329,
63,
3576,
18,
15330,
65,
1648,
943,
2173,
16936,
16,
203,
5411,
315,
2747,
1059,
1534,
9230,
4442,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
1234,
18,
1132,
1545,
2254,
5034,
24899,
2107,
951,
39,
23317,
13,
380,
18324,
12193,
8018,
16,
203,
5411,
315,
1248,
7304,
512,
2455,
7070,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
2229,
18,
10012,
422,
1234,
18,
15330,
16,
203,
5411,
315,
4515,
312,
474,
3059,
279,
1679,
6835,
4442,
203,
3639,
364,
261,
11890,
28,
277,
273,
374,
31,
277,
411,
389,
2107,
951,
39,
23317,
31,
277,
27245,
288,
203,
5411,
389,
4626,
49,
474,
12,
3576,
18,
15330,
16,
965,
4963,
49,
474,
1769,
203,
3639,
289,
203,
3639,
312,
474,
329,
63,
3576,
18,
15330,
65,
1011,
389,
2107,
951,
39,
23317,
31,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100
]
|
pragma solidity ^0.8.0;
// SPDX-License-Identifier: SimPL-2.0
pragma experimental ABIEncoderV2;
import "@openzeppelin/[email protected]/proxy/utils/Initializable.sol";
import "@openzeppelin/[email protected]/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/[email protected]/utils/math/SafeMath.sol";
import "@openzeppelin/[email protected]/utils/Address.sol";
import "@openzeppelin/[email protected]/token/ERC20/IERC20.sol";
import "@openzeppelin/[email protected]/token/ERC721/IERC721.sol";
import "@openzeppelin/[email protected]/token/ERC721/ERC721.sol";
import "../governance/RoleControl.sol";
import "./ThemisFinanceToken.sol";
import "../uniswap/IUniswapV3Oracle.sol";
import "../uniswap/IUniswapV3PoolWhite.sol";
import "../interfaces/IThemisAuction.sol";
import "../interfaces/IThemisBorrowCompoundStorage.sol";
import "../interfaces/IThemisLendCompoundStorage.sol";
contract ThemisBorrowCompound is IThemisBorrowCompoundStorage,IThemisLendCompoundStorage,RoleControl,Initializable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
event UserBorrow(address indexed user, uint256 indexed tokenId, uint256 indexed pid, uint256 bid, uint256 value, uint256 amount,uint256 borrowRate,address apply721Address, uint256 startBlock);
event UserReturn(address indexed user, uint256 indexed bid,uint256 pid, uint256 amount,uint256 interests,uint256 platFormInterests);
event TransferToAuction(uint256 indexed bid, uint256 indexed tokenId,uint256 pid);
event SettlementBorrowEvent(uint256 indexed bid,uint256 pid,uint256 amount,uint256 interests,uint256 platFormInterests);
event AddNftV3WhiteListEvent(uint256 indexed position,address sender,address token0,address token1);
event SetNftV3WhiteListEvent(uint256 indexed position,address sender,address beforeToken0,address beforeToken1,address afterToken0,address afterToken1);
event SetBorrowPoolOverdueRateEvent(uint256 indexed pid,address sender,uint256 beforeOverdueRate,uint256 afterOverdueRate);
event SetSpecial721BorrowRateEvent(address indexed special72,address sender,uint256 beforeRate,uint256 afterRate);
event ApplyRateEvent(address indexed sender,address apply721Address,uint256 specialMaxRate,uint256 tokenId);
event setSettlementBorrowAuthEvent(address indexed sender,address user,bool flag);
event TransferInterestToLendEvent(address indexed sender,uint256 pid,address toUser,uint256 interests);
event SetInterestPlatformRateEvent(address indexed sender,uint256 beforeValue,uint256 afterValue);
event SetFunderEvent(address indexed sender,address beforeVal,address afterVal);
event FunderClaimEvent(address indexed sender,uint256 pid,uint256 amount);
event MinSettingCollateralEvent(address indexed sender,uint256 pid,uint256 beforeVal,uint256 afterVal);
event PausePoolEvent(address indexed sender,uint256 pid,bool flag);
event ChangeUniswapV3OracleEvent(address indexed sender,address beforeVal,address afterVal);
mapping(address => mapping(uint256 => BorrowUserInfo)) public borrowUserInfos;
// Mapping from holder address to their (enumerable) set of owned borrow id
mapping (address => mapping (uint256 => EnumerableSet.UintSet)) private _holderBorrowIds;
mapping (address => EnumerableSet.UintSet) private _holderBorrowPoolIds;
BorrowInfo[] public borrowInfo;
IERC721 public uniswapV3;
address public themisAuction ;
IThemisLendCompound public lendCompound;
CompoundBorrowPool[] public borrowPoolInfo;
address[] public ______________________back; // Invalid field, before nftV3Token0WhiteList
address[] public ______________________back1; // Invalid field, before nftV3Token1WhiteList
address[] public special721Arr;
mapping(address => Special721Info) public special721Info;
mapping(address => UserApplyRate) public userApplyRate;
IUniswapV3Oracle public uniswapV3Oracle;
uint256 public constant blockPerDay = 5760;
uint256 public globalDefault = 650;
mapping(address=>bool) public settlementBorrowAuth;
mapping(uint256 => uint256) public badDebtPrincipal;
mapping(uint256 => uint256) public badDebtInterest;
address public funder;
uint256 public interestPlatformRate;
mapping(uint256 => uint256) public funderPoolInterest; //pid => amount
mapping(uint256 => uint256) public minSettingCollateral;// pid => min amount
modifier onlyLendVistor {
require(address(lendCompound) == msg.sender, "not lend vistor allow.");
_;
}
modifier onlySettlementVistor {
require(settlementBorrowAuth[msg.sender], "not settlement borrow vistor allow.");
_;
}
modifier onlyFunderVistor {
require(funder == msg.sender, "not funder vistor allow.");
_;
}
modifier authContractAccessChecker {
if(msg.sender.isContract() || tx.origin != msg.sender){
require(hasRole(keccak256("CONTRACT_ACCESS_ROLE"),msg.sender), "not whitelist vistor allow.");
}
_;
}
function doInitialize(address _uniswapV3,address _uniswapV3Oracle, IThemisLendCompound _iThemisLendCompound,address _themisAuction,uint256 _globalDefault,uint256 _interestPlatformRate) public initializer{
require(_globalDefault < 1_000,"The maximum ratio has been exceeded.");
require(_interestPlatformRate < 10_000,"The maximum ratio has been exceeded.");
_governance = msg.sender;
_grantRole(PAUSER_ROLE, msg.sender);
uniswapV3 = IERC721(_uniswapV3);
uniswapV3Oracle = IUniswapV3Oracle(_uniswapV3Oracle);
lendCompound = _iThemisLendCompound;
themisAuction = _themisAuction;
globalDefault = _globalDefault;
settlementBorrowAuth[themisAuction] = true;
interestPlatformRate = _interestPlatformRate;
}
function checkNftV3WhiteList(uint256 tokenId) public view returns(bool flag) {
return IUniswapV3PoolWhite(0x502f11922661D072f91b73ae981eeedB236cb944).checkV3PoolWhiteList(tokenId);
}
function changeUniswapV3Oracle(address _uniswapV3Oracle) external onlyGovernance{
address _beforeVal = address(uniswapV3Oracle);
uniswapV3Oracle = IUniswapV3Oracle(_uniswapV3Oracle);
emit ChangeUniswapV3OracleEvent(msg.sender,_beforeVal,_uniswapV3Oracle);
}
function setMinSettingCollateral(uint256 _pid,uint256 _minAmount) external onlyGovernance{
uint256 _beforeVal = minSettingCollateral[_pid];
minSettingCollateral[_pid] = _minAmount;
emit MinSettingCollateralEvent(msg.sender,_pid,_beforeVal,_minAmount);
}
function setInterestPlatformRate(uint256 _interestPlatformRate) external onlyGovernance{
require(_interestPlatformRate < 10_000,"The maximum ratio has been exceeded.");
uint256 _beforeValue = interestPlatformRate;
interestPlatformRate = _interestPlatformRate;
emit SetInterestPlatformRateEvent(msg.sender,_beforeValue,_interestPlatformRate);
}
function setSettlementBorrowAuth(address _user,bool _flag) external onlyGovernance{
settlementBorrowAuth[_user] = _flag;
emit setSettlementBorrowAuthEvent(msg.sender,_user,_flag);
}
function pausePool(uint256 _pid) external onlyRole(PAUSER_ROLE){
CompoundBorrowPool memory _borrowPool = borrowPoolInfo[_pid];
_grantRole(keccak256("VAR_PAUSE_POOL_ACCESS_ROLE"), _borrowPool.token);
emit PausePoolEvent(msg.sender,_pid,true);
}
function unpausePool(uint256 _pid) external onlyGovernance{
CompoundBorrowPool memory _borrowPool = borrowPoolInfo[_pid];
_revokeRole(keccak256("VAR_PAUSE_POOL_ACCESS_ROLE"), _borrowPool.token);
emit PausePoolEvent(msg.sender,_pid,false);
}
function addBorrowPool(address borrowToken,address lendCToken) external onlyLendVistor{
borrowPoolInfo.push(CompoundBorrowPool({
token: borrowToken,
ctoken: lendCToken,
curBorrow: 0,
curBowRate: 0,
lastShareBlock: block.number,
globalBowShare: 0,
globalLendInterestShare: 0,
totalMineInterests: 0,
overdueRate: 800
}));
}
function setSpecial721BorrowRate(address special721,uint256 rate,string memory name) external onlyGovernance{
require(rate < 1000,"The maximum ratio has been exceeded.");
uint256 beforeRate = special721Info[special721].rate;
special721Info[special721].name = name;
special721Info[special721].rate = rate;
bool flag = true;
for(uint i=0;i<special721Arr.length;i++){
if(special721Arr[i] == special721){
flag = false;
break;
}
}
if(flag){
special721Arr[special721Arr.length] = special721;
}
emit SetSpecial721BorrowRateEvent(special721,msg.sender,beforeRate,rate);
}
function setBorrowPoolOverdueRate(uint256 pid,uint256 overdueRate) external onlyGovernance{
CompoundBorrowPool storage _borrowPool = borrowPoolInfo[pid];
uint256 beforeOverdueRate = _borrowPool.overdueRate;
_borrowPool.overdueRate = overdueRate;
emit SetBorrowPoolOverdueRateEvent(pid,msg.sender,beforeOverdueRate,overdueRate);
}
function setFunder(address _funder) external onlyGovernance{
address _beforeVal = funder;
funder = _funder;
emit SetFunderEvent(msg.sender,_beforeVal,_funder);
}
function funderClaim(uint256 _pid,uint256 _amount) external onlyFunderVistor{
uint256 _totalAmount = funderPoolInterest[_pid];
require(_totalAmount >= _amount,"Wrong amount.");
funderPoolInterest[_pid] = funderPoolInterest[_pid].sub(_amount);
CompoundBorrowPool memory _borrowPool = borrowPoolInfo[_pid];
checkPoolPause(_borrowPool.token);
IERC20(_borrowPool.token).safeTransfer(funder,_amount);
emit FunderClaimEvent(msg.sender,_pid,_amount);
}
function transferInterestToLend(uint256 pid,address toUser,uint256 interests) onlyLendVistor external{
checkPoolPause(borrowPoolInfo[pid].token);
IERC20(borrowPoolInfo[pid].token).safeTransfer(toUser,interests);
emit TransferInterestToLendEvent(msg.sender,pid,toUser,interests);
}
function getUserMaxBorrowAmount(uint256 pid, uint256 tokenId, uint256 borrowAmount,address _user) public view returns(uint256 _maxBorrowAmount,bool _flag){
require(checkNftV3WhiteList(tokenId),"Borrow error.Not uniswap V3 white list NFT.");
CompoundBorrowPool memory _borrowPool = borrowPoolInfo[pid];
(uint256 _value,) = uniswapV3Oracle.getTWAPQuoteNft(tokenId, _borrowPool.token);
(,uint256 _borrowRate,,,,) = getUserApplyRate(_user);
_maxBorrowAmount = _value.mul(_borrowRate).div(1000);
_flag = _maxBorrowAmount >= borrowAmount;
}
function v3NFTBorrow(uint256 pid, uint256 tokenId, uint256 borrowAmount) public authContractAccessChecker nonReentrant whenNotPaused {
require(checkNftV3WhiteList(tokenId),"Borrow error.Not uniswap V3 white list NFT.");
BorrowUserInfo storage _user = borrowUserInfos[msg.sender][pid];
CompoundBorrowPool memory _borrowPool = borrowPoolInfo[pid];
checkPoolPause(_borrowPool.token);
(uint256 _value,) = uniswapV3Oracle.getTWAPQuoteNft(tokenId, _borrowPool.token);
require(_value > minSettingCollateral[pid],"The value of collateral is too low.");
(,uint256 _borrowRate,,,,) = getUserApplyRate(msg.sender);
uint256 _maxBorrowAmount = _value.mul(_borrowRate).div(1000);
require(_maxBorrowAmount >= borrowAmount, 'Exceeds the maximum loanable amount');
_upGobalBorrowInfo(pid,borrowAmount,1);
borrowInfo.push(
BorrowInfo({
user: msg.sender,
pid: pid,
// borrowType: 1,
tokenId: tokenId,
borrowValue: _value,
auctionValue: 0,
amount: borrowAmount,
repaidAmount: 0,
startBowShare: _borrowPool.globalBowShare,
// borrowDay: 0,
startBlock: block.number,
returnBlock: 0,
interests: 0,
state: 1
})
);
uint256 _bid = borrowInfo.length - 1;
_user.currTotalBorrow = _user.currTotalBorrow.add(borrowAmount);
if(_holderBorrowIds[msg.sender][pid].length() == 0){
_holderBorrowPoolIds[msg.sender].add(pid);
}
_holderBorrowIds[msg.sender][pid].add(_bid);
uniswapV3.transferFrom(msg.sender, address(this), tokenId);
lendCompound.loanTransferToken(pid,msg.sender,borrowAmount);
emit UserBorrow(msg.sender, tokenId, pid, _bid, _value, borrowAmount,_borrowRate,userApplyRate[msg.sender].apply721Address, block.number);
}
function userReturn(uint256 bid,uint256 repayAmount) public authContractAccessChecker nonReentrant whenNotPaused{
// 2021-1-18 when the collateral is to be cleared and transferred to auction, repayment can be carried out
// require(!isBorrowOverdue(bid), 'borrow is overdue');
BorrowInfo storage _borrowInfo = borrowInfo[bid];
require(_borrowInfo.user == msg.sender, 'not owner');
CompoundBorrowPool memory _borrowPool = borrowPoolInfo[_borrowInfo.pid];
checkPoolPause(_borrowPool.token);
BorrowUserInfo storage _user = borrowUserInfos[msg.sender][_borrowInfo.pid];
uint256 _borrowInterests = _pendingReturnInterests(bid);
require(repayAmount >= _borrowInterests,"Not enough to repay interest.");
uint256 _repayAllAmount = _borrowInfo.amount.add(_borrowInterests);
if(repayAmount > _repayAllAmount){
repayAmount = _repayAllAmount;
}
uint256 _repayPrincipal = repayAmount.sub(_borrowInterests);
uint256 _userBalance = IERC20(_borrowPool.token).balanceOf(msg.sender);
require(_userBalance >= repayAmount, 'not enough amount.');
_upGobalBorrowInfo(_borrowInfo.pid,_repayPrincipal,2);
uint256 _platFormInterests = _borrowInterests.mul(interestPlatformRate).div(10_000);
_updateRealReturnInterest(_borrowInfo.pid,_borrowInterests.sub(_platFormInterests));
_user.currTotalBorrow = _user.currTotalBorrow.sub(_repayPrincipal);
if(_repayPrincipal == _borrowInfo.amount){
_holderBorrowIds[msg.sender][_borrowInfo.pid].remove(bid);
if(_user.currTotalBorrow == 0){
if(_holderBorrowIds[msg.sender][_borrowInfo.pid].length() == 0){
_holderBorrowPoolIds[msg.sender].remove(_borrowInfo.pid);
}
}
_borrowInfo.returnBlock = block.number;
_borrowInfo.state = 2;
uniswapV3.transferFrom(address(this), msg.sender, _borrowInfo.tokenId);
}else{
_borrowInfo.amount = _borrowInfo.amount.sub(_repayPrincipal);
_borrowInfo.startBowShare = _borrowPool.globalBowShare;
}
_borrowInfo.repaidAmount = _borrowInfo.repaidAmount.add(_repayPrincipal);
_borrowInfo.interests = _borrowInfo.interests.add(_borrowInterests);
IERC20(_borrowPool.token).safeTransferFrom(msg.sender, address(this), repayAmount);
if(_platFormInterests > 0){
funderPoolInterest[_borrowInfo.pid] = funderPoolInterest[_borrowInfo.pid].add(_platFormInterests);
}
IERC20(_borrowPool.token).safeApprove(address(lendCompound),0);
IERC20(_borrowPool.token).safeApprove(address(lendCompound),_repayPrincipal);
lendCompound.repayTransferToken(_borrowInfo.pid,_repayPrincipal);
emit UserReturn(msg.sender, bid,_borrowInfo.pid, _repayPrincipal,_borrowInterests,_platFormInterests);
}
function applyRate(address special721,uint256 tokenId) external nonReentrant whenNotPaused{
uint256 _confRate = special721Info[special721].rate;
require(_confRate>0,"This 721 Contract not setting.");
userApplyRate[msg.sender].apply721Address = special721;
userApplyRate[msg.sender].specialMaxRate = _confRate;
userApplyRate[msg.sender].tokenId = tokenId;
emit ApplyRateEvent(msg.sender,special721,_confRate,tokenId);
}
function getUserApplyRate(address user) public view returns(string memory name,uint256 userMaxRate,uint256 defaultRate,uint256 tokenId,address apply721Address,bool signed){
defaultRate = globalDefault;
apply721Address = userApplyRate[user].apply721Address;
signed = false;
if(apply721Address!=address(0)){
tokenId = userApplyRate[user].tokenId;
address tokenOwner = IERC721(apply721Address).ownerOf(tokenId);
if(user == tokenOwner){
userMaxRate = userApplyRate[user].specialMaxRate;
signed = true;
name = special721Info[apply721Address].name;
}
}
if(userMaxRate == 0){
userMaxRate = defaultRate;
}
}
function transferToAuction(uint256 bid) external nonReentrant whenNotPaused{
require(isBorrowOverdue(bid), 'can not auction now');
BorrowInfo storage _borrowInfo = borrowInfo[bid];
require(_borrowInfo.state == 1, 'borrow state error.');
address _userAddr = _borrowInfo.user;
CompoundBorrowPool storage _borrowPool = borrowPoolInfo[_borrowInfo.pid];
checkPoolPause(_borrowPool.token);
BorrowUserInfo storage _user = borrowUserInfos[_userAddr][_borrowInfo.pid];
_borrowInfo.state = 9;
_borrowInfo.interests = _pendingReturnInterests(bid);
_user.currTotalBorrow = _user.currTotalBorrow.sub(_borrowInfo.amount);
_holderBorrowIds[_userAddr][_borrowInfo.pid].remove(bid);
if(_holderBorrowIds[_userAddr][_borrowInfo.pid].length() == 0){
_holderBorrowPoolIds[_userAddr].remove(_borrowInfo.pid);
}
badDebtPrincipal[_borrowInfo.pid] = badDebtPrincipal[_borrowInfo.pid].add(_borrowInfo.amount);
badDebtInterest[_borrowInfo.pid] = badDebtInterest[_borrowInfo.pid].add(_borrowInfo.interests);
_upGobalBorrowInfo(_borrowInfo.pid,_borrowInfo.amount,2);
lendCompound.transferToAuctionUpBorrow(_borrowInfo.pid,_borrowInfo.amount);
(uint256 _value,) = uniswapV3Oracle.getTWAPQuoteNft(_borrowInfo.tokenId, _borrowPool.token);
_borrowInfo.auctionValue = _value;
IThemisAuction(themisAuction).toAuction(address(uniswapV3),_borrowInfo.tokenId,bid,_borrowPool.token,_borrowInfo.auctionValue,_borrowInfo.interests);
uniswapV3.transferFrom(address(this), themisAuction, _borrowInfo.tokenId);
emit TransferToAuction(bid, _borrowInfo.tokenId,_borrowInfo.pid);
}
function settlementBorrow(uint256 bid) public onlySettlementVistor nonReentrant whenNotPaused{
BorrowInfo storage _borrowInfo = borrowInfo[bid];
require(_borrowInfo.state == 9, 'error status');
CompoundBorrowPool storage _borrowPool = borrowPoolInfo[_borrowInfo.pid];
checkPoolPause(_borrowPool.token);
_borrowInfo.state = 8;
_borrowInfo.returnBlock = block.number;
uint256 totalReturn = _borrowInfo.amount.add(_borrowInfo.interests);
badDebtPrincipal[_borrowInfo.pid] = badDebtPrincipal[_borrowInfo.pid].sub(_borrowInfo.amount);
badDebtInterest[_borrowInfo.pid] = badDebtInterest[_borrowInfo.pid].sub(_borrowInfo.interests);
uint256 _platFormInterests = _borrowInfo.interests.mul(interestPlatformRate).div(10_000);
_updateRealReturnInterest(_borrowInfo.pid,_borrowInfo.interests.sub(_platFormInterests));
IERC20(_borrowPool.token).safeTransferFrom(msg.sender, address(this), totalReturn);
if(_platFormInterests > 0){
funderPoolInterest[_borrowInfo.pid] = funderPoolInterest[_borrowInfo.pid].add(_platFormInterests);
}
IERC20(_borrowPool.token).safeApprove(address(lendCompound),0);
IERC20(_borrowPool.token).safeApprove(address(lendCompound),_borrowInfo.amount);
lendCompound.settlementRepayTransferToken(_borrowInfo.pid,_borrowInfo.amount);
emit SettlementBorrowEvent(bid, _borrowInfo.pid,_borrowInfo.amount,_borrowInfo.interests,_platFormInterests);
}
function getSpecial721Length() external view returns(uint256){
return special721Arr.length;
}
function pendingReturnInterests(uint256 bid) external view returns(uint256) {
if (isBorrowOverdue(bid)) {
return 0;
}
return _pendingReturnInterests(bid);
}
function checkPoolPause(address _token) public view {
require(!hasRole(keccak256("VAR_PAUSE_POOL_ACCESS_ROLE"),_token),"This pool has been suspended.");
}
function _pendingReturnInterests(uint256 bid) private view returns(uint256) {
BorrowInfo memory _borrowInfo = borrowInfo[bid];
CompoundBorrowPool memory _borrowPool = borrowPoolInfo[_borrowInfo.pid];
uint256 addBowShare = _calAddBowShare(_borrowPool.curBowRate,_borrowPool.lastShareBlock,block.number);
return _borrowPool.globalBowShare.add(addBowShare).sub(_borrowInfo.startBowShare).mul(_borrowInfo.amount).div(1e12);
}
function getGlobalLendInterestShare(uint256 pid) external view returns(uint256 globalLendInterestShare){
globalLendInterestShare = borrowPoolInfo[pid].globalLendInterestShare;
}
function isBorrowOverdue(uint256 bid) public view returns(bool) {
BorrowInfo memory _borrowInfo = borrowInfo[bid];
CompoundBorrowPool memory _borrowPool = borrowPoolInfo[_borrowInfo.pid];
(uint256 _currValue,) = uniswapV3Oracle.getTWAPQuoteNft(_borrowInfo.tokenId, _borrowPool.token);
uint256 auctionThreshold = _currValue.mul(_borrowPool.overdueRate).div(1000);
uint256 interests = _pendingReturnInterests(bid);
if (interests.add(_borrowInfo.amount) > auctionThreshold) {
return true;
}else{
return false;
}
}
function updateBorrowPool(uint256 pid ) external onlyLendVistor{
_updateCompound(pid);
}
function getBorrowIdsOfOwnerAndPoolId(address owner,uint256 pid) external view returns (uint256[] memory) {
uint256[] memory tokens = new uint256[](_holderBorrowIds[owner][pid].length());
for (uint256 i = 0; i < _holderBorrowIds[owner][pid].length(); i++) {
tokens[i] = _holderBorrowIds[owner][pid].at(i);
}
return tokens;
}
function getBorrowPoolIdsOfOwner(address owner) external view returns (uint256[] memory) {
uint256[] memory tokens = new uint256[](_holderBorrowPoolIds[owner].length());
for (uint256 i = 0; i < _holderBorrowPoolIds[owner].length(); i++) {
tokens[i] = _holderBorrowPoolIds[owner].at(i);
}
return tokens;
}
function getFundUtilization(uint256 pid) public view returns(uint256) {
CompoundLendPool memory _lendPool = lendCompound.lendPoolInfo(pid);
if (_lendPool.curSupply.add(_lendPool.curBorrow) <= 0) {
return 0;
}
return _lendPool.curBorrow.mul(1e12).div(_lendPool.curSupply.add(_lendPool.curBorrow));
}
function getBorrowingRate(uint256 pid) public view returns(uint256) {
return getFundUtilization(pid).mul(200000000000).div(1e12).add(25000000000);
}
function getLendingRate(uint256 pid) public view returns(uint256) {
return getFundUtilization(pid).mul(getBorrowingRate(pid)).div(1e12);
}
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) public pure returns (address token0, address token1) {
require(tokenA != tokenB, 'V3 NFT: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'V3 NFT: ZERO_ADDRESS');
}
function _upGobalBorrowInfo(uint256 pid,uint256 amount,uint optType) private{
CompoundBorrowPool storage _borrowPool = borrowPoolInfo[pid];
if(optType == 1){
_borrowPool.curBorrow = _borrowPool.curBorrow.add(amount);
}else{
_borrowPool.curBorrow = _borrowPool.curBorrow.sub(amount);
}
_updateCompound(pid);
}
//must excute after Compound pool value update
function _updateCompound(uint256 _pid) private {
CompoundBorrowPool storage _borrowPool = borrowPoolInfo[_pid];
if (_borrowPool.lastShareBlock >= block.number) {
return;
}
uint256 addBowShare = _calAddBowShare(_borrowPool.curBowRate,_borrowPool.lastShareBlock,block.number);
_borrowPool.lastShareBlock = block.number;
_borrowPool.curBowRate = getBorrowingRate(_pid);
_borrowPool.globalBowShare = _borrowPool.globalBowShare.add(addBowShare);
}
function _updateRealReturnInterest(uint256 _pid,uint256 _interests) private {
if(_interests > 0){
CompoundBorrowPool storage _borrowPool = borrowPoolInfo[_pid];
uint256 lpSupply = ThemisFinanceToken(_borrowPool.ctoken).totalSupply();
if (lpSupply > 0) {
_borrowPool.globalLendInterestShare = _borrowPool.globalLendInterestShare.add(_interests.mul(1e12).div(lpSupply));
}
}
}
function _calAddBowShare(uint256 _curBowRate,uint256 _lastShareBlock,uint256 _blockNuber) pure internal returns(uint256 addBowShare){
addBowShare = _curBowRate.mul(_blockNuber.sub(_lastShareBlock)).div(blockPerDay * 365);
}
}
| must excute after Compound pool value update | function _updateCompound(uint256 _pid) private {
CompoundBorrowPool storage _borrowPool = borrowPoolInfo[_pid];
if (_borrowPool.lastShareBlock >= block.number) {
return;
}
uint256 addBowShare = _calAddBowShare(_borrowPool.curBowRate,_borrowPool.lastShareBlock,block.number);
_borrowPool.lastShareBlock = block.number;
_borrowPool.curBowRate = getBorrowingRate(_pid);
_borrowPool.globalBowShare = _borrowPool.globalBowShare.add(addBowShare);
}
| 5,409,487 | [
1,
11926,
3533,
624,
1839,
21327,
2845,
460,
1089,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
2725,
16835,
12,
11890,
5034,
389,
6610,
13,
3238,
288,
203,
3639,
21327,
38,
15318,
2864,
2502,
389,
70,
15318,
2864,
273,
29759,
2864,
966,
63,
67,
6610,
15533,
203,
3639,
309,
261,
67,
70,
15318,
2864,
18,
2722,
9535,
1768,
1545,
1203,
18,
2696,
13,
288,
203,
5411,
327,
31,
203,
3639,
289,
203,
202,
202,
11890,
5034,
527,
38,
543,
9535,
273,
389,
771,
986,
38,
543,
9535,
24899,
70,
15318,
2864,
18,
1397,
38,
543,
4727,
16,
67,
70,
15318,
2864,
18,
2722,
9535,
1768,
16,
2629,
18,
2696,
1769,
203,
7010,
3639,
389,
70,
15318,
2864,
18,
2722,
9535,
1768,
273,
1203,
18,
2696,
31,
203,
3639,
389,
70,
15318,
2864,
18,
1397,
38,
543,
4727,
273,
2882,
15318,
310,
4727,
24899,
6610,
1769,
203,
3639,
389,
70,
15318,
2864,
18,
6347,
38,
543,
9535,
273,
389,
70,
15318,
2864,
18,
6347,
38,
543,
9535,
18,
1289,
12,
1289,
38,
543,
9535,
1769,
203,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;
import './third_party/INonfungiblePositionManager.sol';
import './third_party/IPeripheryImmutableState.sol';
import './third_party/IPeripheryPayments.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC721/ERC721.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
import '@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol';
/// A contract used to lock liquidity for Uniswap V3 pools
contract LiquidityLock is ERC721, IERC721Receiver, IERC777Recipient {
/// @dev The ID of the next token that will be minted. Skips 0
uint256 private _nextId = 1;
/// @dev A map of token IDs to the associated position data
mapping(uint256 => LockedPosition) private _positions;
/// @dev A map of Uniswap token IDs to their corresponding token IDs in this lock contract
mapping(uint256 => uint256) private _uniswapTokenIdsToLock;
/// Details about the liquidity position that are locked in this contract
struct LockedPosition {
/// @dev The address of the Uniswap V3 position manager contract that controls the liquidity
address positionManager;
/// @dev The token id of the position in the position manager contract
uint256 uniswapTokenId;
/// @dev Address of the token0 contract
address token0;
/// @dev Address of the token1 contract
address token1;
/// @dev The liquidity at the time this contract took control of the position. Note: This number
/// may differ from the original liquidity of the position if, for example, the position
/// operator decreased their liquidity before locking the remaining liquidity in this contract.
uint128 initialLiquidity;
/// @dev Tme amount by which the initial liquidity has already been decreased
uint128 decreasedLiquidity;
/// @dev The unix timestamp when the liquidity starts to unlock
uint256 startUnlockingTimestamp;
/// @dev The unix timestamp when the liquidity finishes unlocking
uint256 finishUnlockingTimestamp;
}
// Events
/// @notice Emitted when a token owner decreases and withdraws liquidity
event WithdrawLiquidity(uint256 indexed tokenId, address indexed recipient, uint128 liquidity);
/// @notice Emitted when a token owner collects and withdraws tokens without decreasing liquidity
event CollectTokens(uint256 indexed tokenId, address indexed recipient);
/// @notice Emitted when a Uniswap token is returned after the lock duration has completely elapsed
event ReturnUniswap(uint256 indexed lockTokenId, uint256 indexed uniswapTokenId, address indexed owner);
constructor() ERC721('Uniswap V3 Liquidity Lock', 'UV3LL') {}
// MARK: - LiquidityLock public interface
/// @notice Returns the original owner of the provided Uniswap token ID that is currently locked
/// by this contract
function ownerOfUniswap(uint256 _uniswapTokenId) external view returns (address owner) {
uint256 _lockTokenId = _uniswapTokenIdsToLock[_uniswapTokenId];
require(_lockTokenId != 0, 'No lock token');
return ownerOf(_lockTokenId);
}
/// @notice Returns the token ID of the locked position token that wraps the provided uniswap token
function lockTokenId(uint256 _uniswapTokenId) external view returns (uint256 _lockTokenId) {
_lockTokenId = _uniswapTokenIdsToLock[_uniswapTokenId];
require(_lockTokenId != 0, 'No lock token');
}
/// @notice Returns the token ID of the Uniswap token that is locked and represented by the provided
/// lock token ID
function uniswapTokenId(uint256 _lockTokenId) external view returns (uint256 _uniswapTokenId) {
require(_exists(_lockTokenId), 'Invalid token ID');
LockedPosition storage position = _positions[_lockTokenId];
_uniswapTokenId = position.uniswapTokenId;
}
/// @notice Returns the total amount of liquidity available to be withdrawn at this time
function availableLiquidity(uint256 tokenId) public view returns (uint128) {
require(_exists(tokenId), 'Invalid token ID');
LockedPosition storage position = _positions[tokenId];
uint256 timestamp = block.timestamp;
if (position.startUnlockingTimestamp > timestamp) {
// The liquidity has not yet begun to unlock
return 0;
}
if (timestamp >= position.finishUnlockingTimestamp) {
// The liquidity is completely unlocked, so all remaining liquidity is available
return position.initialLiquidity - position.decreasedLiquidity;
}
// The ratio of liquidity available in parts per thousand (not percent)
uint256 unlockPerMille = ((timestamp - position.startUnlockingTimestamp) * 1000) /
(position.finishUnlockingTimestamp - position.startUnlockingTimestamp);
uint256 unlockedLiquidity = (position.initialLiquidity * unlockPerMille) / 1000;
return uint128(unlockedLiquidity - position.decreasedLiquidity);
}
/// @notice This function allows you to decrease your liquidity position and withdraw any collected tokens
/// or ETH. The provided `liquidity` value must be less than or equal to the total available liquidity, which
/// can be obtained by calling `availableLiquidity`.
/// @dev It works by wrapping multiple different calls to the position manager contract, specifically:
/// * `decreaseLiquidity` - Decrease the liquidity position and increase the amount of tokens owed
/// * `collect` - Collect the owed, sending them (temporarily) to the position manager contract
/// * `unwrapWETH9` - If either of the tokens is WETH, unwrap them to ETH and transfer them to the recipient
/// * `sweepToken` - Transfer any tokens left in the position manager contract to the recipient
function withdrawLiquidity(
uint256 tokenId,
address recipient,
uint128 liquidity,
uint256 amount0Min,
uint256 amount1Min,
uint256 deadline
) external {
require(ERC721.ownerOf(tokenId) == msg.sender, 'Not authorized');
LockedPosition storage position = _positions[tokenId];
uint128 available = availableLiquidity(tokenId);
require(liquidity <= available, 'Liquidity unavailable');
position.decreasedLiquidity += liquidity;
// Decrease the liquidity position
INonfungiblePositionManager manager = INonfungiblePositionManager(position.positionManager);
INonfungiblePositionManager.DecreaseLiquidityParams memory decreaseParams = INonfungiblePositionManager
.DecreaseLiquidityParams({
tokenId: position.uniswapTokenId,
liquidity: liquidity,
amount0Min: amount0Min,
amount1Min: amount1Min,
deadline: deadline
});
manager.decreaseLiquidity(decreaseParams);
// Collect all available tokens into the position manager contract
_collectAndWithdrawTokens(tokenId, recipient, amount0Min, amount1Min);
emit WithdrawLiquidity(tokenId, recipient, liquidity);
}
/// @notice Collect any tokens due from fees or from decreasing liquidity
/// @param tokenId The token ID of the locked position token, not the wrapped uniswap token
/// @dev If you have the Uniswap token ID but not the lock token ID, you can call `getLockTokenId`,
/// and pass the Uniswap token ID to receive the lock token ID.
function collectAndWithdrawTokens(
uint256 tokenId,
address recipient,
uint256 amount0Min,
uint256 amount1Min
) external {
require(ERC721.ownerOf(tokenId) == msg.sender, 'Not authorized');
_collectAndWithdrawTokens(tokenId, recipient, amount0Min, amount1Min);
emit CollectTokens(tokenId, recipient);
}
/// @notice Returns the locked Uniswap token to the original owner and deletes the lock token
/// @dev This can only be done if the current timestamp is greater than the finish timestamp
/// of the locked position.
function returnUniswapToken(uint256 tokenId) external {
require(ERC721.ownerOf(tokenId) == msg.sender, 'Not authorized');
LockedPosition storage position = _positions[tokenId];
uint256 _uniswapTokenId = position.uniswapTokenId;
uint256 timestamp = block.timestamp;
require(timestamp >= position.finishUnlockingTimestamp, 'Not completely unlocked');
IERC721 manager = IERC721(position.positionManager);
manager.safeTransferFrom(address(this), msg.sender, _uniswapTokenId);
delete _uniswapTokenIdsToLock[_uniswapTokenId];
delete _positions[tokenId];
_burn(tokenId);
emit ReturnUniswap(tokenId, _uniswapTokenId, msg.sender);
}
// MARK: - IERC721Receiver
function onERC721Received(
address, /*operator*/
address from,
uint256 tokenId,
bytes calldata data
) external override returns (bytes4) {
INonfungiblePositionManager manager = INonfungiblePositionManager(msg.sender);
(
/* uint96 nonce */,
/* address operator */,
address token0,
address token1,
/* uint24 fee */,
/* int24 tickLower */,
/* int24 tickUpper */,
uint128 liquidity,
/* uint256 feeGrowthInside0LastX128 */,
/* uint256 feeGrowthInside1LastX128 */,
/* uint128 tokensOwed0 */,
/* uint128 tokensOwed1 */
) = manager.positions(tokenId);
require(liquidity > 0, 'Not enough liquidity to lock');
require(token0 != address(0) && token1 != address(0), 'Invalid token address');
// Sanity check length of provided data before trying to decode.
require(data.length == 64, 'Invalid data field. Must contain two timestamps.');
// The `data` parameter is expected to contain the start and finish timestamps
(uint256 startTimestamp, uint256 finishTimestamp) = abi.decode(data, (uint256, uint256));
// The start and finish timestamps should be in the future, and the finish timestamp should be
// farther in the future than the start timestamp
uint256 timestamp = block.timestamp;
require(startTimestamp >= timestamp && finishTimestamp > startTimestamp, 'Invalid timestamps');
// Mint an NFT representing this locked position with `from` as the owner
_mint(from, _nextId);
_positions[_nextId] = LockedPosition({
positionManager: msg.sender,
uniswapTokenId: tokenId,
token0: token0,
token1: token1,
initialLiquidity: liquidity,
decreasedLiquidity: 0,
startUnlockingTimestamp: startTimestamp,
finishUnlockingTimestamp: finishTimestamp
});
_uniswapTokenIdsToLock[tokenId] = _nextId;
_nextId++;
return this.onERC721Received.selector;
}
// MARK: - IERC777Recipient
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external {
// todo: Do we need to do any validation here?
}
// MARK: - Private helper functions
/// @dev See docs for `collectAndWithdrawTokens`
function _collectAndWithdrawTokens(
uint256 tokenId,
address recipient,
uint256 amount0Min,
uint256 amount1Min
) private {
LockedPosition storage position = _positions[tokenId];
// Collect all available tokens into the position manager contract
INonfungiblePositionManager manager = INonfungiblePositionManager(position.positionManager);
INonfungiblePositionManager.CollectParams memory collectParams = INonfungiblePositionManager.CollectParams({
tokenId: position.uniswapTokenId,
recipient: address(0), // address(0) is a magic number referring to the address of the position manager contract
amount0Max: type(uint128).max,
amount1Max: type(uint128).max
});
manager.collect(collectParams);
// Step 3: Unwrap WETH or sweep tokens
IPeripheryImmutableState state = IPeripheryImmutableState(position.positionManager);
address WETHAddress = state.WETH9();
IPeripheryPayments payments = IPeripheryPayments(position.positionManager);
unwrapWETHOrSweep(position.token0, recipient, amount0Min, payments, WETHAddress);
unwrapWETHOrSweep(position.token1, recipient, amount1Min, payments, WETHAddress);
}
/// @dev Either call `unwrapWETH9` or `sweepToken` on the provided payments contract depending on
/// whether the token address refers to WETH or a regular ERC-20 token.
function unwrapWETHOrSweep(
address tokenAddress,
address recipient,
uint256 amountMinimum,
IPeripheryPayments payments,
address WETHAddress
) private {
if (tokenAddress == WETHAddress) {
payments.unwrapWETH9(amountMinimum, recipient);
} else {
payments.sweepToken(tokenAddress, amountMinimum, recipient);
}
}
}
| Sanity check length of provided data before trying to decode. The `data` parameter is expected to contain the start and finish timestamps The start and finish timestamps should be in the future, and the finish timestamp should be farther in the future than the start timestamp Mint an NFT representing this locked position with `from` as the owner | function onERC721Received(
address, /*operator*/
address from,
uint256 tokenId,
bytes calldata data
) external override returns (bytes4) {
INonfungiblePositionManager manager = INonfungiblePositionManager(msg.sender);
(
address token0,
address token1,
uint128 liquidity,
) = manager.positions(tokenId);
require(liquidity > 0, 'Not enough liquidity to lock');
require(token0 != address(0) && token1 != address(0), 'Invalid token address');
require(data.length == 64, 'Invalid data field. Must contain two timestamps.');
(uint256 startTimestamp, uint256 finishTimestamp) = abi.decode(data, (uint256, uint256));
uint256 timestamp = block.timestamp;
require(startTimestamp >= timestamp && finishTimestamp > startTimestamp, 'Invalid timestamps');
_mint(from, _nextId);
_positions[_nextId] = LockedPosition({
positionManager: msg.sender,
uniswapTokenId: tokenId,
token0: token0,
token1: token1,
initialLiquidity: liquidity,
decreasedLiquidity: 0,
startUnlockingTimestamp: startTimestamp,
finishUnlockingTimestamp: finishTimestamp
});
_uniswapTokenIdsToLock[tokenId] = _nextId;
_nextId++;
return this.onERC721Received.selector;
}
| 14,104,315 | [
1,
55,
10417,
866,
769,
434,
2112,
501,
1865,
8374,
358,
2495,
18,
1021,
1375,
892,
68,
1569,
353,
2665,
358,
912,
326,
787,
471,
4076,
11267,
1021,
787,
471,
4076,
11267,
1410,
506,
316,
326,
3563,
16,
471,
326,
4076,
2858,
1410,
506,
10247,
1136,
316,
326,
3563,
2353,
326,
787,
2858,
490,
474,
392,
423,
4464,
5123,
333,
8586,
1754,
598,
1375,
2080,
68,
487,
326,
3410,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
603,
654,
39,
27,
5340,
8872,
12,
203,
3639,
1758,
16,
1748,
9497,
5549,
203,
3639,
1758,
628,
16,
203,
3639,
2254,
5034,
1147,
548,
16,
203,
3639,
1731,
745,
892,
501,
203,
565,
262,
3903,
3849,
1135,
261,
3890,
24,
13,
288,
203,
3639,
2120,
265,
12125,
75,
1523,
2555,
1318,
3301,
273,
2120,
265,
12125,
75,
1523,
2555,
1318,
12,
3576,
18,
15330,
1769,
203,
3639,
261,
203,
5411,
1758,
1147,
20,
16,
203,
5411,
1758,
1147,
21,
16,
203,
5411,
2254,
10392,
4501,
372,
24237,
16,
203,
3639,
262,
273,
3301,
18,
12388,
12,
2316,
548,
1769,
203,
203,
3639,
2583,
12,
549,
372,
24237,
405,
374,
16,
296,
1248,
7304,
4501,
372,
24237,
358,
2176,
8284,
203,
3639,
2583,
12,
2316,
20,
480,
1758,
12,
20,
13,
597,
1147,
21,
480,
1758,
12,
20,
3631,
296,
1941,
1147,
1758,
8284,
203,
203,
3639,
2583,
12,
892,
18,
2469,
422,
5178,
16,
296,
1941,
501,
652,
18,
6753,
912,
2795,
11267,
1093,
1769,
203,
3639,
261,
11890,
5034,
787,
4921,
16,
2254,
5034,
4076,
4921,
13,
273,
24126,
18,
3922,
12,
892,
16,
261,
11890,
5034,
16,
2254,
5034,
10019,
203,
203,
3639,
2254,
5034,
2858,
273,
1203,
18,
5508,
31,
203,
3639,
2583,
12,
1937,
4921,
1545,
2858,
597,
4076,
4921,
405,
787,
4921,
16,
296,
1941,
11267,
8284,
203,
203,
3639,
389,
81,
474,
12,
2080,
16,
389,
4285,
548,
1769,
203,
3639,
389,
12388,
63,
67,
4285,
548,
65,
273,
3488,
329,
2555,
12590,
203,
5411,
2
]
|
pragma solidity ^0.4.18;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
event PrivateFundEnabled();
event PrivateFundDisabled();
bool public paused = false;
bool public privateFundEnabled = true;
/**
* @dev Modifier to make a function callable only when the contract is private fund not end.
*/
modifier whenPrivateFundDisabled() {
require(!privateFundEnabled);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is private fund end.
*/
modifier whenPrivateFundEnabled() {
require(privateFundEnabled);
_;
}
/**
* @dev called by the owner to end private fund, triggers stopped state
*/
function disablePrivateFund() onlyOwner whenPrivateFundEnabled public {
privateFundEnabled = false;
emit PrivateFundDisabled();
}
/**
* @dev called by the owner to unlock private fund, returns to normal state
*/
function enablePrivateFund() onlyOwner whenPrivateFundDisabled public {
privateFundEnabled = true;
emit PrivateFundEnabled();
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20 {
uint256 public totalSupply;
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);
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);
}
contract GlobalSharingEconomyCoin is Pausable, ERC20 {
using SafeMath for uint256;
event BatchTransfer(address indexed owner, bool value);
string public name;
string public symbol;
uint8 public decimals;
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
mapping (address => bool) allowedBatchTransfers;
constructor() public {
name = "GlobalSharingEconomyCoin";
symbol = "GSE";
decimals = 8;
totalSupply = 10000000000 * 10 ** uint256(decimals);
balances[msg.sender] = totalSupply;
allowedBatchTransfers[msg.sender] = true;
}
function transfer(address _to, uint256 _value) whenNotPaused 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 setBatchTransfer(address _address, bool _value) public onlyOwner returns (bool) {
allowedBatchTransfers[_address] = _value;
emit BatchTransfer(_address, _value);
return true;
}
function getBatchTransfer(address _address) public onlyOwner view returns (bool) {
return allowedBatchTransfers[_address];
}
/**
* 只允许项目方空投,如果项目方禁止批量转币,也同时禁用空投
*/
function airdrop(address[] _funds, uint256 _amount) public whenNotPaused whenPrivateFundEnabled returns (bool) {
require(allowedBatchTransfers[msg.sender]);
uint256 fundslen = _funds.length;
// 根据gaslimit的限制,超过300个地址的循环基本就无法成功执行了
require(fundslen > 0 && fundslen < 300);
uint256 totalAmount = 0;
for (uint i = 0; i < fundslen; ++i){
balances[_funds[i]] = balances[_funds[i]].add(_amount);
totalAmount = totalAmount.add(_amount);
emit Transfer(msg.sender, _funds[i], _amount);
}
// 如果执行失败,则会回滚整个交易
require(balances[msg.sender] >= totalAmount);
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
/**
* 允许交易所和项目放方批量转币
* _funds: 批量转币地址
* _amounts: 每个地址的转币数量,长度必须跟_funds的长度相同
*/
function batchTransfer(address[] _funds, uint256[] _amounts) public whenNotPaused whenPrivateFundEnabled returns (bool) {
require(allowedBatchTransfers[msg.sender]);
uint256 fundslen = _funds.length;
uint256 amountslen = _amounts.length;
require(fundslen == amountslen && fundslen > 0 && fundslen < 300);
uint256 totalAmount = 0;
for (uint i = 0; i < amountslen; ++i){
totalAmount = totalAmount.add(_amounts[i]);
}
require(balances[msg.sender] >= totalAmount);
for (uint j = 0; j < amountslen; ++j) {
balances[_funds[j]] = balances[_funds[j]].add(_amounts[j]);
emit Transfer(msg.sender, _funds[j], _amounts[j]);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused 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 whenNotPaused 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];
}
} | * @dev called by the owner to end private fund, triggers stopped state/ | function disablePrivateFund() onlyOwner whenPrivateFundEnabled public {
privateFundEnabled = false;
emit PrivateFundDisabled();
}
| 12,061,758 | [
1,
11777,
635,
326,
3410,
358,
679,
3238,
284,
1074,
16,
11752,
9627,
919,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
4056,
6014,
42,
1074,
1435,
1338,
5541,
1347,
6014,
42,
1074,
1526,
1071,
288,
203,
565,
3238,
42,
1074,
1526,
273,
629,
31,
203,
565,
3626,
8726,
42,
1074,
8853,
5621,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x1B39b961B697b7582af98385A910dCFD7db261ab/sources/contracts/Jangles.sol | ** Role Modifiers */ | modifier onlyMinter() {
require(hasRole(MINTER_ROLE, _msgSender()), 'Caller is not a minter');
_;
}
| 3,009,502 | [
1,
2996,
3431,
3383,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
9606,
1338,
49,
2761,
1435,
288,
203,
3639,
2583,
12,
5332,
2996,
12,
6236,
2560,
67,
16256,
16,
389,
3576,
12021,
1435,
3631,
296,
11095,
353,
486,
279,
1131,
387,
8284,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
* Library easily handles the cases of overflow as well as underflow.
* Also ensures that balance does nto get naegative
*/
library SafeMath {
// multiplies two values safely and returns result
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;
}
// devides two values safely and returns result
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;
}
// subtracts two values safely and returns result
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
// adds two values safely and returns result
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
// Event to log whenever the ownership is tranferred
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value, bytes data);
}
/**
* @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;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
bytes memory empty;
Transfer(msg.sender, _to, _value, empty);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
*/
contract StandardToken is ERC20, BasicToken {
// tracks the allowance of address.
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
bytes memory empty;
Transfer(_from, _to, _value, empty);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool) {
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title ERC23Receiver interface
* @dev see https://github.com/ethereum/EIPs/issues/223
*/
contract ERC223Receiver {
struct TokenStruct {
address sender;
uint256 value;
bytes data;
bytes4 sig;
}
/**
* @dev Fallback function. Our ICO contract should implement this contract to receve ERC23 compatible tokens.
* ERC23 protocol checks if contract has implemented this fallback method or not.
* If this method is not implemented then tokens are not sent.
* This method is introduced to avoid loss of tokens
*
* @param _from The address which will transfer the tokens.
* @param _value Amount of tokens received.
* @param _data Data sent along with transfer request.
*/
function tokenFallback(address _from, uint256 _value, bytes _data) public pure {
TokenStruct memory tkn;
tkn.sender = _from;
tkn.value = _value;
tkn.data = _data;
// uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24);
// tkn.sig = bytes4(u);
/* tkn variable is analogue of msg variable of Ether transaction
* tkn.sender is person who initiated this token transaction (analogue of msg.sender)
* tkn.value the number of tokens that were sent (analogue of msg.value)
* tkn.data is data of token transaction (analogue of msg.data)
* tkn.sig is 4 bytes signature of function
* if data of token transaction is a function execution
*/
}
}
/**
* @title ERC23 interface
* @dev see https://github.com/ethereum/EIPs/issues/223
*/
contract ERC223 {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function transfer(address to, uint256 value, bytes data) public returns (bool);
function transfer(address to, uint256 value, bytes data, string custom_fallback) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value, bytes indexed data);
}
/**
* @title Standard ERC223Token token
*
* @dev Implementation of the ERC23 token.
* @dev https://github.com/ethereum/EIPs/issues/223
*/
contract ERC223Token is ERC223, StandardToken {
using SafeMath for uint256;
/**
* @dev Function that is called when a user or another contract wants to transfer funds .
* This is method where you can supply fallback function name and that function will be triggered.
* This method is added as part of ERC23 standard
*
* @param _to The address which will receive the tokens.
* @param _value Amount of tokens received.
* @param _data Data sent along with transfer request.
* @param _custom_fallback Name of the method which should be called after transfer happens. If this method does not exists on contract then transaction will fail
*/
function transfer(address _to, uint256 _value, bytes _data, string _custom_fallback) public returns (bool success) {
// check if receiving is contract
if(isContract(_to)) {
// validate the address and balance
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
// invoke custom fallback function
assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data));
Transfer(msg.sender, _to, _value, _data);
return true;
}
else {
// receiver is not a contract so perform normal transfer to address
return transferToAddress(_to, _value, _data);
}
}
/**
* @dev Function that is called when a user or another contract wants to transfer funds .
* You can pass extra data which can be tracked in event.
* This method is added as part of ERC23 standard
*
* @param _to The address which will receive the tokens.
* @param _value Amount of tokens received.
* @param _data Data sent along with transfer request.
*/
function transfer(address _to, uint256 _value, bytes _data) public returns (bool success) {
// check if receiver is contract address
if(isContract(_to)) {
// invoke transfer request to contract
return transferToContract(_to, _value, _data);
}
else {
// invoke transfer request to normal user wallet address
return transferToAddress(_to, _value, _data);
}
}
/**
* @dev Standard function transfer similar to ERC20 transfer with no _data .
* Added due to backwards compatibility reasons .
*
* @param _to The address which will receive the tokens.
* @param _value Amount of tokens received.
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
//standard function transfer similar to ERC20 transfer with no _data
//added due to backwards compatibility reasons
bytes memory empty;
// check if receiver is contract address
if(isContract(_to)) {
// invoke transfer request to contract
return transferToContract(_to, _value, empty);
}
else {
// invoke transfer request to normal user wallet address
return transferToAddress(_to, _value, empty);
}
}
/**
* @dev assemble the given address bytecode. If bytecode exists then the _addr is a contract.
*
* @param _addr The address which need to be checked if contract address or wallet address
*/
function isContract(address _addr) private view returns (bool is_contract) {
uint256 length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length > 0);
}
/**
* @dev Function that is called when transaction target is an address. This is private method.
*
* @param _to The address which will receive the tokens.
* @param _value Amount of tokens received.
* @param _data Data sent along with transfer request.
*/
function transferToAddress(address _to, uint256 _value, bytes _data) private returns (bool success) {
// validate the address and balance
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
// Log the transfer event
Transfer(msg.sender, _to, _value, _data);
return true;
}
/**
* @dev Function that is called when transaction target is a contract. This is private method.
*
* @param _to The address which will receive the tokens.
* @param _value Amount of tokens received.
* @param _data Data sent along with transfer request.
*/
function transferToContract(address _to, uint256 _value, bytes _data) private returns (bool success) {
// validate the address and balance
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
// call fallback function of contract
ERC223Receiver receiver = ERC223Receiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
// Log the transfer event
Transfer(msg.sender, _to, _value, _data);
return true;
}
}
/**
* @title PalestinoToken
* @dev Very simple ERC23 Token example, where all tokens are pre-assigned to the creator.
*/
contract PalestinoToken is ERC223Token, Ownable {
string public constant name = "Palestino";
string public constant symbol = "PALE";
uint256 public constant decimals = 3;
uint256 constant INITIAL_SUPPLY = 10000000 * 1E3;
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
function PalestinoToken() public {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
/**
* @dev if ether is sent to this address, send it back.
*/
function () public {
revert();
}
}
/**
* @title PalestinoTokenSale
* @dev This is ICO Contract.
* This class accepts the token address as argument to talk with contract.
* Once contract is deployed, funds are transferred to ICO smart contract address and then distributed with investor.
* Sending funds to this ensures that no more than desired tokens are sold.
*/
contract PalestinoTokenSale is Ownable, ERC223Receiver {
using SafeMath for uint256;
// The token being sold, this holds reference to main token contract
PalestinoToken public token;
// timestamp when sale starts
uint256 public startingTimestamp = 1515974400;
// amount of token to be sold on sale
uint256 public maxTokenForSale = 10000000 * 1E3;
// amount of token sold so far
uint256 public totalTokenSold;
// amount of ether raised in sale
uint256 public totalEtherRaised;
// ether raised per wallet
mapping(address => uint256) public etherRaisedPerWallet;
// walle which will receive the ether funding
address public wallet;
// is contract close and ended
bool internal isClose = false;
struct RoundStruct {
uint256 number;
uint256 fromAmount;
uint256 toAmount;
uint256 price;
}
RoundStruct[9] public rounds;
// token purchsae event
event TokenPurchase(address indexed _purchaser, address indexed _beneficiary, uint256 _value, uint256 _amount, uint256 _timestamp);
// manual transfer by admin for external purchase
event TransferManual(address indexed _from, address indexed _to, uint256 _value, string _message);
/**
* @dev Constructor that initializes token contract with token address in parameter
*/
function PalestinoTokenSale(address _token, address _wallet) public {
// set token
token = PalestinoToken(_token);
// set wallet
wallet = _wallet;
// setup rounds
rounds[0] = RoundStruct(0, 0 , 2500000E3, 0.01 ether);
rounds[1] = RoundStruct(1, 2500000E3, 3000000E3, 0.02 ether);
rounds[2] = RoundStruct(2, 3000000E3, 3500000E3, 0.03 ether);
rounds[3] = RoundStruct(3, 3500000E3, 4000000E3, 0.06 ether);
rounds[4] = RoundStruct(4, 4000000E3, 4500000E3, 0.10 ether);
rounds[5] = RoundStruct(5, 4500000E3, 5000000E3, 0.18 ether);
rounds[6] = RoundStruct(6, 5000000E3, 5500000E3, 0.32 ether);
rounds[7] = RoundStruct(7, 5500000E3, 6000000E3, 0.57 ether);
rounds[8] = RoundStruct(8, 6000000E3, 10000000E3, 1.01 ether);
}
/**
* @dev Function that validates if the purchase is valid by verifying the parameters
*
* @param value Amount of ethers sent
* @param amount Total number of tokens user is trying to buy.
*
* @return checks various conditions and returns the bool result indicating validity.
*/
function isValidPurchase(uint256 value, uint256 amount) internal constant returns (bool) {
// check if timestamp is falling in the range
bool validTimestamp = startingTimestamp <= block.timestamp;
// check if value of the ether is valid
bool validValue = value != 0;
// check if the tokens available in contract for sale
bool validAmount = maxTokenForSale.sub(totalTokenSold) >= amount && amount > 0;
// validate if all conditions are met
return validTimestamp && validValue && validAmount && !isClose;
}
/**
* @dev Function that returns the current round
*
* @return checks various conditions and returns the current round.
*/
function getCurrentRound() public constant returns (RoundStruct) {
for(uint256 i = 0 ; i < rounds.length ; i ++) {
if(rounds[i].fromAmount <= totalTokenSold && totalTokenSold < rounds[i].toAmount) {
return rounds[i];
}
}
}
/**
* @dev Function that returns the estimate token round by sending amount
*
* @param amount Amount of tokens expected
*
* @return checks various conditions and returns the estimate token round.
*/
function getEstimatedRound(uint256 amount) public constant returns (RoundStruct) {
for(uint256 i = 0 ; i < rounds.length ; i ++) {
if(rounds[i].fromAmount > (totalTokenSold + amount)) {
return rounds[i - 1];
}
}
return rounds[rounds.length - 1];
}
/**
* @dev Function that returns the maximum token round by sending amount
*
* @param amount Amount of tokens expected
*
* @return checks various conditions and returns the maximum token round.
*/
function getMaximumRound(uint256 amount) public constant returns (RoundStruct) {
for(uint256 i = 0 ; i < rounds.length ; i ++) {
if((totalTokenSold + amount) <= rounds[i].toAmount) {
return rounds[i];
}
}
}
/**
* @dev Function that calculates the tokens which should be given to user by iterating over rounds
*
* @param value Amount of ethers sent
*
* @return checks various conditions and returns the token amount.
*/
function getTokenAmount(uint256 value) public constant returns (uint256 , uint256) {
// assume we are sending no tokens
uint256 totalAmount = 0;
// interate until we have some value left for buying
while(value > 0) {
// get current round by passing queue value also
RoundStruct memory estimatedRound = getEstimatedRound(totalAmount);
// find tokens left in current round.
uint256 tokensLeft = estimatedRound.toAmount.sub(totalTokenSold.add(totalAmount));
// derive tokens can be bought in current round with round price
uint256 tokensBuys = value.mul(1E3).div(estimatedRound.price);
// check if it is last round and still value left
if(estimatedRound.number == rounds[rounds.length - 1].number) {
// its last round
// no tokens left in round and still got value
if(tokensLeft == 0 && value > 0) {
return (totalAmount , value);
}
}
// if tokens left > tokens buy
if(tokensLeft >= tokensBuys) {
totalAmount = totalAmount.add(tokensBuys);
value = 0;
return (totalAmount , value);
} else {
uint256 tokensLeftValue = tokensLeft.mul(estimatedRound.price).div(1E3);
totalAmount = totalAmount.add(tokensLeft);
value = value.sub(tokensLeftValue);
}
}
return (0 , value);
}
/**
* @dev Default fallback method which will be called when any ethers are sent to contract
*/
function() public payable {
buyTokens(msg.sender);
}
/**
* @dev Function that is called either externally or by default payable method
*
* @param beneficiary who should receive tokens
*/
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
// value sent by buyer
uint256 value = msg.value;
// calculate token amount from the ethers sent
var (amount, leftValue) = getTokenAmount(value);
// if there is any left value then return
if(leftValue > 0) {
value = value.sub(leftValue);
msg.sender.transfer(leftValue);
}
// validate the purchase
require(isValidPurchase(value , amount));
// update the state to log the sold tokens and raised ethers.
totalTokenSold = totalTokenSold.add(amount);
totalEtherRaised = totalEtherRaised.add(value);
etherRaisedPerWallet[msg.sender] = etherRaisedPerWallet[msg.sender].add(value);
// transfer tokens from contract balance to beneficiary account. calling ERC223 method
bytes memory empty;
token.transfer(beneficiary, amount, empty);
// log event for token purchase
TokenPurchase(msg.sender, beneficiary, value, amount, now);
}
/**
* @dev transmit token for a specified address.
* This is owner only method and should be called using web3.js if someone is trying to buy token using bitcoin or any other altcoin.
*
* @param _to The address to transmit to.
* @param _value The amount to be transferred.
* @param _message message to log after transfer.
*/
function transferManual(address _to, uint256 _value, string _message) onlyOwner public returns (bool) {
require(_to != address(0));
// transfer tokens manually from contract balance
token.transfer(_to , _value);
TransferManual(msg.sender, _to, _value, _message);
return true;
}
/**
* @dev Method called by owner to change the wallet address
*/
function setWallet(address _wallet) onlyOwner public {
wallet = _wallet;
}
/**
* @dev Method called by owner of contract to withdraw funds
*/
function withdraw() onlyOwner public {
wallet.transfer(this.balance);
}
/**
* @dev close contract
* This will send remaining token balance to owner
* This will distribute available funds across team members
*/
function close() onlyOwner public {
// send remaining tokens back to owner.
uint256 tokens = token.balanceOf(this);
token.transfer(owner , tokens);
// withdraw funds
withdraw();
// mark the flag to indicate closure of the contract
isClose = true;
}
} | * @dev Function that returns the estimate token round by sending amount @param amount Amount of tokens expected @return checks various conditions and returns the estimate token round./ | function getEstimatedRound(uint256 amount) public constant returns (RoundStruct) {
for(uint256 i = 0 ; i < rounds.length ; i ++) {
if(rounds[i].fromAmount > (totalTokenSold + amount)) {
return rounds[i - 1];
}
}
return rounds[rounds.length - 1];
}
| 12,771,365 | [
1,
2083,
716,
1135,
326,
11108,
1147,
3643,
635,
5431,
3844,
225,
3844,
16811,
434,
2430,
2665,
327,
4271,
11191,
4636,
471,
1135,
326,
11108,
1147,
3643,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
202,
915,
4774,
334,
17275,
11066,
12,
11890,
5034,
3844,
13,
1071,
5381,
1135,
261,
11066,
3823,
13,
288,
203,
202,
202,
1884,
12,
11890,
5034,
277,
273,
374,
274,
277,
411,
21196,
18,
2469,
274,
277,
965,
13,
288,
203,
1082,
202,
430,
12,
27950,
63,
77,
8009,
2080,
6275,
405,
261,
4963,
1345,
55,
1673,
397,
3844,
3719,
288,
203,
9506,
202,
2463,
21196,
63,
77,
300,
404,
15533,
203,
1082,
202,
97,
203,
202,
202,
97,
203,
203,
202,
202,
2463,
21196,
63,
27950,
18,
2469,
300,
404,
15533,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.15;
/*
Utilities & Common Modifiers
*/
contract Utils {
/**
constructor
*/
function Utils() {
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != 0x0);
_;
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this));
_;
}
// Overflow protected math functions
/**
@dev returns the sum of _x and _y, asserts if the calculation overflows
@param _x value 1
@param _y value 2
@return sum
*/
function safeAdd(uint256 _x, uint256 _y) internal returns (uint256) {
uint256 z = _x + _y;
assert(z >= _x);
return z;
}
/**
@dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number
@param _x minuend
@param _y subtrahend
@return difference
*/
function safeSub(uint256 _x, uint256 _y) internal returns (uint256) {
assert(_x >= _y);
return _x - _y;
}
/**
@dev returns the product of multiplying _x by _y, asserts if the calculation overflows
@param _x factor 1
@param _y factor 2
@return product
*/
function safeMul(uint256 _x, uint256 _y) internal returns (uint256) {
uint256 z = _x * _y;
assert(_x == 0 || z / _x == _y);
return z;
}
}
/*
ERC20 Standard Token interface
*/
contract IERC20Token {
// these functions aren't abstract since the compiler emits automatically generated getter functions as external
function name() public constant returns (string) { name; }
function symbol() public constant returns (string) { symbol; }
function decimals() public constant returns (uint8) { decimals; }
function totalSupply() public constant returns (uint256) { totalSupply; }
function balanceOf(address _owner) public constant returns (uint256 balance) { _owner; balance; }
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { _owner; _spender; remaining; }
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
/**
ERC20 Standard Token implementation
*/
contract ERC20Token is IERC20Token, Utils {
string public standard = "Token 0.1";
string public name = "";
string public symbol = "";
uint8 public decimals = 0;
uint256 public totalSupply = 0;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
@dev constructor
@param _name token name
@param _symbol token symbol
@param _decimals decimal points, for display purposes
*/
function ERC20Token(string _name, string _symbol, uint8 _decimals) {
require(bytes(_name).length > 0 && bytes(_symbol).length > 0); // validate input
name = _name;
symbol = _symbol;
decimals = _decimals;
}
/**
@dev send coins
throws on any error rather then return a false flag to minimize user errors
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transfer(address _to, uint256 _value)
public
validAddress(_to)
returns (bool success)
{
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
@dev an account/contract attempts to get the coins
throws on any error rather then return a false flag to minimize user errors
@param _from source address
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transferFrom(address _from, address _to, uint256 _value)
public
validAddress(_from)
validAddress(_to)
returns (bool success)
{
allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value);
balanceOf[_from] = safeSub(balanceOf[_from], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
Transfer(_from, _to, _value);
return true;
}
/**
@dev allow another account/contract to spend some tokens on your behalf
throws on any error rather then return a false flag to minimize user errors
also, to minimize the risk of the approve/transferFrom attack vector
(see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), approve has to be called twice
in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value
@param _spender approved address
@param _value allowance amount
@return true if the approval was successful, false if it wasn't
*/
function approve(address _spender, uint256 _value)
public
validAddress(_spender)
returns (bool success)
{
// if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal
require(_value == 0 || allowance[msg.sender][_spender] == 0);
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
}
/*
Owned contract interface
*/
contract IOwned {
// this function isn't abstract since the compiler emits automatically generated getter functions as external
function owner() public constant returns (address) { owner; }
function transferOwnership(address _newOwner) public;
function acceptOwnership() public;
}
/*
Provides support and utilities for contract ownership
*/
contract Owned is IOwned {
address public owner;
address public newOwner;
event OwnerUpdate(address _prevOwner, address _newOwner);
/**
@dev constructor
*/
function Owned() {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
assert(msg.sender == owner);
_;
}
/**
@dev allows transferring the contract ownership
the new owner still needs to accept the transfer
can only be called by the contract owner
@param _newOwner new contract owner
*/
function transferOwnership(address _newOwner) public ownerOnly {
require(_newOwner != owner);
newOwner = _newOwner;
}
/**
@dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = 0x0;
}
}
/*
Token Holder interface
*/
contract ITokenHolder is IOwned {
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public;
}
contract TokenHolder is ITokenHolder, Owned, Utils {
/**
@dev constructor
*/
function TokenHolder() {
}
/**
@dev withdraws tokens held by the contract and sends them to an account
can only be called by the owner
@param _token ERC20 token contract address
@param _to account to receive the new amount
@param _amount amount to withdraw
*/
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount)
public
ownerOnly
validAddress(_token)
validAddress(_to)
notThis(_to)
{
assert(_token.transfer(_to, _amount));
}
}
contract CLRSToken is ERC20Token, TokenHolder {
///////////////////////////////////////// VARIABLE INITIALIZATION /////////////////////////////////////////
uint256 constant public CLRS_UNIT = 10 ** 18;
uint256 public totalSupply = 86374977 * CLRS_UNIT;
// Constants
uint256 constant public maxIcoSupply = 48369987 * CLRS_UNIT; // ICO pool allocation
uint256 constant public Company = 7773748 * CLRS_UNIT; // Company pool allocation
uint256 constant public Bonus = 16411245 * CLRS_UNIT; // Bonus Allocation
uint256 constant public Bounty = 1727500 * CLRS_UNIT; // Bounty Allocation
uint256 constant public advisorsAllocation = 4318748 * CLRS_UNIT; // Advisors Allocation
uint256 constant public CLRSinTeamAllocation = 7773748 * CLRS_UNIT; // CLRSin Team allocation
// Addresses of Patrons
address public constant ICOSTAKE = 0xd82896Ea0B5848dc3b75bbECc747947F64077b7c;
address public constant COMPANY_STAKE_1 = 0x19333A742dcd220683C2231c0FAaCcb9c810C0B5;
address public constant COMPANY_STAKE_2 = 0x19333A742dcd220683C2231c0FAaCcb9c810C0B5;
address public constant COMPANY_STAKE_3 = 0x19333A742dcd220683C2231c0FAaCcb9c810C0B5;
address public constant COMPANY_STAKE_4 = 0x19333A742dcd220683C2231c0FAaCcb9c810C0B5;
address public constant COMPANY_STAKE_5 = 0x19333A742dcd220683C2231c0FAaCcb9c810C0B5;
address public constant ADVISOR_1 = 0xf0eB71d3b31fEe5D15220A2ac418A784c962Eb53;
address public constant ADVISOR_2 = 0xFd6b0691Cd486B4124fFD9FBe9e013463868E2B4;
address public constant ADVISOR_3 = 0xCFb32aFA7752170043aaC32794397C8673778765;
address public constant ADVISOR_4 = 0x08441513c0Fc653a739F34A97eF6B2B05609a4E4;
address public constant ADVISOR_5 = 0xFd6b0691Cd486B4124fFD9FBe9e013463868E2B4;
address public constant TEAM_1 = 0xc4896CB7486ed8821B525D858c85D4321e8e5685;
address public constant TEAM_2 = 0x304765b9c3072E54b7397E2F55D1463BD62802C3;
address public constant TEAM_3 = 0x46abC1d38573E8726c6C0568CC01f35fE5FF4765;
address public constant TEAM_4 = 0x36Bf4b1DDd796eaf1f962cB0E0327C15096fae41;
address public constant TEAM_5 = 0xc4896CB7486ed8821B525D858c85D4321e8e5685;
address public constant BONUS_1 = 0x19333A742dcd220683C2231c0FAaCcb9c810C0B5;
address public constant BONUS_2 = 0x19333A742dcd220683C2231c0FAaCcb9c810C0B5;
address public constant BONUS_3 = 0x19333A742dcd220683C2231c0FAaCcb9c810C0B5;
address public constant BONUS_4 = 0x19333A742dcd220683C2231c0FAaCcb9c810C0B5;
address public constant BONUS_5 = 0x19333A742dcd220683C2231c0FAaCcb9c810C0B5;
address public constant BOUNTY_1 = 0x19333A742dcd220683C2231c0FAaCcb9c810C0B5;
address public constant BOUNTY_2 = 0x19333A742dcd220683C2231c0FAaCcb9c810C0B5;
address public constant BOUNTY_3 = 0x19333A742dcd220683C2231c0FAaCcb9c810C0B5;
address public constant BOUNTY_4 = 0x19333A742dcd220683C2231c0FAaCcb9c810C0B5;
address public constant BOUNTY_5 = 0x19333A742dcd220683C2231c0FAaCcb9c810C0B5;
// Stakes of COMPANY
uint256 constant public COMPANY_1 = 7773744 * CLRS_UNIT; //token allocated to company1
uint256 constant public COMPANY_2 = 1 * CLRS_UNIT; //token allocated to company1
uint256 constant public COMPANY_3 = 1 * CLRS_UNIT; //token allocated to company1
uint256 constant public COMPANY_4 = 1 * CLRS_UNIT; //token allocated to company1
uint256 constant public COMPANY_5 = 1 * CLRS_UNIT; //token allocated to company1
// Stakes of ADVISORS
uint256 constant public ADVISOR1 = 863750 * CLRS_UNIT; //token allocated to adv1
uint256 constant public ADVISOR2 = 863750 * CLRS_UNIT; //token allocated to adv2
uint256 constant public ADVISOR3 = 431875 * CLRS_UNIT; //token allocated to adv3
uint256 constant public ADVISOR4 = 431875 * CLRS_UNIT; //token allocated to adv4
uint256 constant public ADVISOR5 = 863750 * CLRS_UNIT; //token allocated to adv5
// Stakes of TEAM
uint256 constant public TEAM1 = 3876873 * CLRS_UNIT; //token allocated to team1
uint256 constant public TEAM2 = 3876874 * CLRS_UNIT; //token allocated to team2
uint256 constant public TEAM3 = 10000 * CLRS_UNIT; //token allocated to team3
uint256 constant public TEAM4 = 10000 * CLRS_UNIT; //token allocated to team4
uint256 constant public TEAM5 = 1 * CLRS_UNIT; //token allocated to team5
// Stakes of BONUS
uint256 constant public BONUS1 = 16411241 * CLRS_UNIT; //token allocated to bonus1
uint256 constant public BONUS2 = 1 * CLRS_UNIT; //token allocated to bonus2
uint256 constant public BONUS3 = 1 * CLRS_UNIT; //token allocated to bonus3
uint256 constant public BONUS4 = 1 * CLRS_UNIT; //token allocated to bonus4
uint256 constant public BONUS5 = 1 * CLRS_UNIT; //token allocated to bonus5
// Stakes of BOUNTY
uint256 constant public BOUNTY1 = 1727400 * CLRS_UNIT; //token allocated to bounty1
uint256 constant public BOUNTY2 = 1 * CLRS_UNIT; //token allocated to bounty2
uint256 constant public BOUNTY3 = 1 * CLRS_UNIT; //token allocated bounty3
uint256 constant public BOUNTY4 = 1 * CLRS_UNIT; //token allocated bounty4
uint256 constant public BOUNTY5 = 1 * CLRS_UNIT; //token allocated bounty5
// Variables
uint256 public totalAllocatedToCompany = 0; // Counter to keep track of comapny token allocation
uint256 public totalAllocatedToAdvisor = 0; // Counter to keep track of advisor token allocation
uint256 public totalAllocatedToTEAM = 0; // Counter to keep track of team token allocation
uint256 public totalAllocatedToBONUS = 0; // Counter to keep track of bonus token allocation
uint256 public totalAllocatedToBOUNTY = 0; // Counter to keep track of bounty token allocation
uint256 public remaintokensteam=0;
uint256 public remaintokensadvisors=0;
uint256 public remaintokensbounty=0;
uint256 public remaintokensbonus=0;
uint256 public remaintokenscompany=0;
uint256 public totremains=0;
uint256 public totalAllocated = 0; // Counter to keep track of overall token allocation
uint256 public endTime; // timestamp
bool internal isReleasedToPublic = false; // Flag to allow transfer/transferFrom
bool public isReleasedToadv = false;
bool public isReleasedToteam = false;
///////////////////////////////////////// MODIFIERS /////////////////////////////////////////
// CLRSin Team timelock
/* modifier safeTimelock() {
require(now >= endTime + 52 weeks);
_;
}
// Advisor Team timelock
modifier advisorTimelock() {
require(now >= endTime + 26 weeks);
_;
}*/
///////////////////////////////////////// CONSTRUCTOR /////////////////////////////////////////
function CLRSToken()
ERC20Token("CLRS", "CLRS", 18)
{
balanceOf[ICOSTAKE] = maxIcoSupply; // ico CLRS tokens
balanceOf[COMPANY_STAKE_1] = COMPANY_1; // Company1 CLRS tokens
balanceOf[COMPANY_STAKE_2] = COMPANY_2; // Company2 CLRS tokens
balanceOf[COMPANY_STAKE_3] = COMPANY_3; // Company3 CLRS tokens
balanceOf[COMPANY_STAKE_4] = COMPANY_4; // Company4 CLRS tokens
balanceOf[COMPANY_STAKE_5] = COMPANY_5; // Company5 CLRS tokens
totalAllocatedToCompany = safeAdd(totalAllocatedToCompany, COMPANY_1);
totalAllocatedToCompany = safeAdd(totalAllocatedToCompany, COMPANY_2);
totalAllocatedToCompany = safeAdd(totalAllocatedToCompany, COMPANY_3);
totalAllocatedToCompany = safeAdd(totalAllocatedToCompany, COMPANY_4);
totalAllocatedToCompany = safeAdd(totalAllocatedToCompany, COMPANY_5);
remaintokenscompany=safeSub(Company,totalAllocatedToCompany);
balanceOf[ICOSTAKE]=safeAdd(balanceOf[ICOSTAKE],remaintokenscompany);
balanceOf[BONUS_1] = BONUS1; // bonus1 CLRS tokens
balanceOf[BONUS_2] = BONUS2; // bonus2 CLRS tokens
balanceOf[BONUS_3] = BONUS3; // bonus3 CLRS tokens
balanceOf[BONUS_4] = BONUS4; // bonus4 CLRS tokens
balanceOf[BONUS_5] = BONUS5; // bonus5 CLRS tokens
totalAllocatedToBONUS = safeAdd(totalAllocatedToBONUS, BONUS1);
totalAllocatedToBONUS = safeAdd(totalAllocatedToBONUS, BONUS2);
totalAllocatedToBONUS = safeAdd(totalAllocatedToBONUS, BONUS3);
totalAllocatedToBONUS = safeAdd(totalAllocatedToBONUS, BONUS4);
totalAllocatedToBONUS = safeAdd(totalAllocatedToBONUS, BONUS5);
remaintokensbonus=safeSub(Bonus,totalAllocatedToBONUS);
balanceOf[ICOSTAKE]=safeAdd(balanceOf[ICOSTAKE],remaintokensbonus);
balanceOf[BOUNTY_1] = BOUNTY1; // BOUNTY1 CLRS tokens
balanceOf[BOUNTY_2] = BOUNTY2; // BOUNTY2 CLRS tokens
balanceOf[BOUNTY_3] = BOUNTY3; // BOUNTY3 CLRS tokens
balanceOf[BOUNTY_4] = BOUNTY4; // BOUNTY4 CLRS tokens
balanceOf[BOUNTY_5] = BOUNTY5; // BOUNTY5 CLRS tokens
totalAllocatedToBOUNTY = safeAdd(totalAllocatedToBOUNTY, BOUNTY1);
totalAllocatedToBOUNTY = safeAdd(totalAllocatedToBOUNTY, BOUNTY2);
totalAllocatedToBOUNTY = safeAdd(totalAllocatedToBOUNTY, BOUNTY3);
totalAllocatedToBOUNTY = safeAdd(totalAllocatedToBOUNTY, BOUNTY4);
totalAllocatedToBOUNTY = safeAdd(totalAllocatedToBOUNTY, BOUNTY5);
remaintokensbounty=safeSub(Bounty,totalAllocatedToBOUNTY);
balanceOf[ICOSTAKE]=safeAdd(balanceOf[ICOSTAKE],remaintokensbounty);
allocateAdvisorTokens() ;
allocateCLRSinTeamTokens();
totremains=safeAdd(totremains,remaintokenscompany);
totremains=safeAdd(totremains,remaintokensbounty);
totremains=safeAdd(totremains,remaintokensbonus);
totremains=safeAdd(totremains,remaintokensteam);
totremains=safeAdd(totremains,remaintokensadvisors);
burnTokens(totremains);
totalAllocated += maxIcoSupply+ totalAllocatedToCompany+ totalAllocatedToBONUS + totalAllocatedToBOUNTY; // Add to total Allocated funds
}
///////////////////////////////////////// ERC20 OVERRIDE /////////////////////////////////////////
/**
@dev send coins
throws on any error rather then return a false flag to minimize user errors
in addition to the standard checks, the function throws if transfers are disabled
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, throws if it wasn't
*/
/*function transfer(address _to, uint256 _value) public returns (bool success) {
if (isTransferAllowed() == true) {
assert(super.transfer(_to, _value));
return true;
}
revert();
}
/**
@dev an account/contract attempts to get the coins
throws on any error rather then return a false flag to minimize user errors
in addition to the standard checks, the function throws if transfers are disabled
@param _from source address
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, throws if it wasn't
*/
/* function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if (isTransferAllowed() == true ) {
assert(super.transferFrom(_from, _to, _value));
return true;
}
revert();
}*/
/**
* Allow transfer only after finished
*/
//allows to dissable transfers while minting and in case of emergency
modifier canTransfer() {
require( isTransferAllowedteam()==true );
_;
}
modifier canTransferadv() {
require( isTransferAllowedadv()==true );
_;
}
function transfer(address _to, uint256 _value) canTransfer canTransferadv public returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) canTransfer canTransferadv public returns (bool) {
return super.transferFrom(_from, _to, _value);
}
///////////////////////////////////////// ALLOCATION FUNCTIONS /////////////////////////////////////////
function allocateCLRSinTeamTokens() public returns(bool success) {
require(totalAllocatedToTEAM < CLRSinTeamAllocation);
balanceOf[TEAM_1] = safeAdd(balanceOf[TEAM_1], TEAM1); // TEAM1 CLRS tokens
balanceOf[TEAM_2] = safeAdd(balanceOf[TEAM_2], TEAM2); // TEAM2 CLRS tokens
balanceOf[TEAM_3] = safeAdd(balanceOf[TEAM_3], TEAM3); // TEAM3 CLRS tokens
balanceOf[TEAM_4] = safeAdd(balanceOf[TEAM_4], TEAM4); // TEAM4 CLRS tokens
balanceOf[TEAM_5] = safeAdd(balanceOf[TEAM_5], TEAM5); // TEAM5 CLRS tokens
/*Transfer(0x0, TEAM_1, TEAM1);
Transfer(0x0, TEAM_2, TEAM2);
Transfer(0x0, TEAM_3, TEAM3);
Transfer(0x0, TEAM_4, TEAM4);
Transfer(0x0, TEAM_5, TEAM5);*/
totalAllocatedToTEAM = safeAdd(totalAllocatedToTEAM, TEAM1);
totalAllocatedToTEAM = safeAdd(totalAllocatedToTEAM, TEAM2);
totalAllocatedToTEAM = safeAdd(totalAllocatedToTEAM, TEAM3);
totalAllocatedToTEAM = safeAdd(totalAllocatedToTEAM, TEAM4);
totalAllocatedToTEAM = safeAdd(totalAllocatedToTEAM, TEAM5);
totalAllocated += totalAllocatedToTEAM;
remaintokensteam=safeSub(CLRSinTeamAllocation,totalAllocatedToTEAM);
balanceOf[ICOSTAKE]=safeAdd(balanceOf[ICOSTAKE],remaintokensteam);
return true;
}
function allocateAdvisorTokens() public returns(bool success) {
require(totalAllocatedToAdvisor < advisorsAllocation);
balanceOf[ADVISOR_1] = safeAdd(balanceOf[ADVISOR_1], ADVISOR1);
balanceOf[ADVISOR_2] = safeAdd(balanceOf[ADVISOR_2], ADVISOR2);
balanceOf[ADVISOR_3] = safeAdd(balanceOf[ADVISOR_3], ADVISOR3);
balanceOf[ADVISOR_4] = safeAdd(balanceOf[ADVISOR_4], ADVISOR4);
balanceOf[ADVISOR_5] = safeAdd(balanceOf[ADVISOR_5], ADVISOR5);
/*Transfer(0x0, ADVISOR_1, ADVISOR1);
Transfer(0x0, ADVISOR_2, ADVISOR2);
Transfer(0x0, ADVISOR_3, ADVISOR3);
Transfer(0x0, ADVISOR_4, ADVISOR4);
Transfer(0x0, ADVISOR_5, ADVISOR5);*/
totalAllocatedToAdvisor = safeAdd(totalAllocatedToAdvisor, ADVISOR1);
totalAllocatedToAdvisor = safeAdd(totalAllocatedToAdvisor, ADVISOR2);
totalAllocatedToAdvisor = safeAdd(totalAllocatedToAdvisor, ADVISOR3);
totalAllocatedToAdvisor = safeAdd(totalAllocatedToAdvisor, ADVISOR4);
totalAllocatedToAdvisor = safeAdd(totalAllocatedToAdvisor, ADVISOR5);
totalAllocated += totalAllocatedToAdvisor;
remaintokensadvisors=safeSub(advisorsAllocation,totalAllocatedToAdvisor);
balanceOf[ICOSTAKE]=safeAdd(balanceOf[ICOSTAKE],remaintokensadvisors);
return true;
}
function releaseAdvisorTokens() ownerOnly {
isReleasedToadv = true;
}
function releaseCLRSinTeamTokens() ownerOnly {
isReleasedToteam = true;
}
function burnTokens(uint256 _value) ownerOnly returns(bool success) {
uint256 amountOfTokens = _value;
balanceOf[msg.sender]=safeSub(balanceOf[msg.sender], amountOfTokens);
totalSupply=safeSub(totalSupply, amountOfTokens);
Transfer(msg.sender, 0x0, amountOfTokens);
return true;
}
/**
@dev Function to allow transfers
can only be called by the owner of the contract
Transfers will be allowed regardless after the crowdfund end time.
*/
function allowTransfers() ownerOnly {
isReleasedToPublic = true;
}
function starttime() ownerOnly {
endTime = now;
}
/**
@dev User transfers are allowed/rejected
Transfers are forbidden before the end of the crowdfund
*/
function isTransferAllowedteam() public returns(bool)
{
if (isReleasedToteam==true)
return true;
if(now < endTime + 52 weeks)
{
if(msg.sender==TEAM_1 || msg.sender==TEAM_2 || msg.sender==TEAM_3 || msg.sender==TEAM_4 || msg.sender==TEAM_5)
return false;
}
return true;
}
function isTransferAllowedadv() public returns(bool)
{
if (isReleasedToadv==true)
return true;
if(now < endTime + 26 weeks)
{
if(msg.sender==ADVISOR_1 || msg.sender==ADVISOR_2 || msg.sender==ADVISOR_3 || msg.sender==ADVISOR_4 || msg.sender==ADVISOR_5)
return false;
}
return true;
}
} | Company1 CLRS tokens
| balanceOf[COMPANY_STAKE_1] = COMPANY_1; | 12,811,656 | [
1,
12627,
21,
14934,
13225,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
11013,
951,
63,
10057,
15409,
67,
882,
37,
6859,
67,
21,
65,
273,
13846,
15409,
67,
21,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.4.24;
import "./SafeMath.sol";
import "./Ownable.sol";
contract EmalToken {
// add function prototypes of only those used here
function transferFrom(address _from, address _to, uint256 _value) public returns(bool);
function getBountyAmount() public view returns(uint256);
}
contract EmalBounty is Ownable {
using SafeMath for uint256;
// The token being sold
EmalToken public token;
// Bounty contract state Data structures
enum State {
Active,
Closed
}
// contains current state of bounty contract
State public state;
// Bounty limit in EMAL tokens
uint256 public bountyLimit;
// Count of total number of EML tokens that have been currently allocated to bounty users
uint256 public totalTokensAllocated = 0;
// Count of allocated tokens (not issued only allocated) for each bounty user
mapping(address => uint256) public allocatedTokens;
// Count of allocated tokens issued to each bounty user.
mapping(address => uint256) public amountOfAllocatedTokensGivenOut;
/** @dev Event fired when tokens are allocated to a bounty user account
* @param beneficiary Address that is allocated tokens
* @param tokenCount The amount of tokens that were allocated
*/
event TokensAllocated(address indexed beneficiary, uint256 tokenCount);
event TokensDeallocated(address indexed beneficiary, uint256 tokenCount);
/**
* @dev Event fired when EML tokens are sent to a bounty user
* @param beneficiary Address where the allocated tokens were sent
* @param tokenCount The amount of tokens that were sent
*/
event IssuedAllocatedTokens(address indexed beneficiary, uint256 tokenCount);
/** @param _token Address of the token that will be rewarded for the investors
*/
constructor(address _token) public {
require(_token != address(0));
owner = msg.sender;
token = EmalToken(_token);
state = State.Active;
bountyLimit = token.getBountyAmount();
}
/* Do not accept ETH */
function() external payable {
revert();
}
function closeBounty() public onlyOwner returns(bool){
require( state!=State.Closed );
state = State.Closed;
return true;
}
/** @dev Public function to check if bounty isActive or not
* @return True if Bounty event has ended
*/
function isBountyActive() public view returns(bool) {
if (state==State.Active && totalTokensAllocated<bountyLimit){
return true;
} else {
return false;
}
}
/** @dev Allocates tokens to a bounty user
* @param beneficiary The address of the bounty user
* @param tokenCount The number of tokens to be allocated to this address
*/
function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {
require(beneficiary != address(0));
require(validAllocation(tokenCount));
uint256 tokens = tokenCount;
/* Allocate only the remaining tokens if final contribution exceeds hard cap */
if (totalTokensAllocated.add(tokens) > bountyLimit) {
tokens = bountyLimit.sub(totalTokensAllocated);
}
/* Update state and balances */
allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens);
totalTokensAllocated = totalTokensAllocated.add(tokens);
emit TokensAllocated(beneficiary, tokens);
return true;
}
function validAllocation( uint256 tokenCount ) internal view returns(bool) {
bool isActive = state==State.Active;
bool positiveAllocation = tokenCount>0;
bool bountyLimitNotReached = totalTokensAllocated<bountyLimit;
return isActive && positiveAllocation && bountyLimitNotReached;
}
/** @dev Remove tokens from a bounty user's allocation.
* @dev Used in game based bounty allocation, automatically called from the Sails app
* @param beneficiary The address of the bounty user
* @param tokenCount The number of tokens to be deallocated to this address
*/
function deductAllocatedTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {
require(beneficiary != address(0));
require(tokenCount>0 && tokenCount<=allocatedTokens[beneficiary]);
allocatedTokens[beneficiary] = allocatedTokens[beneficiary].sub(tokenCount);
totalTokensAllocated = totalTokensAllocated.sub(tokenCount);
emit TokensDeallocated(beneficiary, tokenCount);
return true;
}
/** @dev Getter function to check the amount of allocated tokens
* @param beneficiary address of the investor or the bounty user
*/
function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) {
require(beneficiary != address(0));
return allocatedTokens[beneficiary];
}
/** @dev Bounty users will be issued EML Tokens by the sails api,
* @dev after the Bounty has ended to their address
* @param beneficiary address of the bounty user
*/
function issueTokensToAllocatedUsers(address beneficiary) public onlyOwner returns(bool success) {
require(beneficiary!=address(0));
require(allocatedTokens[beneficiary]>0);
uint256 tokensToSend = allocatedTokens[beneficiary];
allocatedTokens[beneficiary] = 0;
amountOfAllocatedTokensGivenOut[beneficiary] = amountOfAllocatedTokensGivenOut[beneficiary].add(tokensToSend);
assert(token.transferFrom(owner, beneficiary, tokensToSend));
emit IssuedAllocatedTokens(beneficiary, tokensToSend);
return true;
}
}
pragma solidity 0.4.24;
import "./SafeMath.sol";
import "./Ownable.sol";
import "./Pausable.sol";
contract EmalToken {
// add function prototypes of only those used here
function transferFrom(address _from, address _to, uint256 _value) public returns(bool);
function getCrowdsaleAmount() public view returns(uint256);
function setStartTimeForTokenTransfers(uint256 _startTime) external;
}
contract EmalWhitelist {
// add function prototypes of only those used here
function isWhitelisted(address investorAddr) public view returns(bool whitelisted);
}
contract EmalCrowdsale is Ownable, Pausable {
using SafeMath for uint256;
// Start and end timestamps
uint256 public startTime;
uint256 public endTime;
// The token being sold
EmalToken public token;
// Whitelist contract used to store whitelisted addresses
EmalWhitelist public list;
// Address where funds are collected
address public multisigWallet;
// Switched to true once token contract is notified of when to enable token transfers
bool private isStartTimeSetForTokenTransfers = false;
// Hard cap in EMAL tokens
uint256 public hardCap;
// Soft cap in EMAL tokens
uint256 constant public soft_cap = 50000000 * (10 ** 18);
// Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments.
uint256 public totalTokensSoldandAllocated = 0;
// Investor contributions made in ether
mapping(address => uint256) public etherInvestments;
// Tokens given to investors who sent ether investments
mapping(address => uint256) public tokensSoldForEther;
// Total ether raised by the Crowdsale
uint256 public totalEtherRaisedByCrowdsale = 0;
// Total number of tokens sold to investors who made payments in ether
uint256 public totalTokensSoldByEtherInvestments = 0;
// Count of allocated tokens for each investor or bounty user
mapping(address => uint256) public allocatedTokens;
// Count of total number of EML tokens that have been currently allocated to Crowdsale investors
uint256 public totalTokensAllocated = 0;
/** @dev Event for EML token purchase using ether
* @param investorAddr Address that paid and got the tokens
* @param paidAmount The amount that was paid (in wei)
* @param tokenCount The amount of tokens that were bought
*/
event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount);
/**
* @dev Event for refund logging
* @param receiver The address that received the refund
* @param amount The amount that is being refunded (in wei)
*/
event Refund(address indexed receiver, uint256 amount);
/** @dev Event fired when EML tokens are allocated to an investor account
* @param beneficiary Address that is allocated tokens
* @param tokenCount The amount of tokens that were allocated
*/
event TokensAllocated(address indexed beneficiary, uint256 tokenCount);
event TokensDeallocated(address indexed beneficiary, uint256 tokenCount);
/** @dev variables and functions which determine conversion rate from ETH to EML
* based on bonuses and current timestamp.
*/
uint256 priceOfEthInUSD = 450;
uint256 bonusPercent1 = 25;
uint256 bonusPercent2 = 15;
uint256 bonusPercent3 = 0;
uint256 priceOfEMLTokenInUSDPenny = 60;
uint256 overridenBonusValue = 0;
function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) {
require( overridenValue > 0 );
require( overridenValue != priceOfEthInUSD);
priceOfEthInUSD = overridenValue;
return true;
}
function getExchangeRate() public view returns(uint256){
return priceOfEthInUSD;
}
function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) {
require( overridenValue > 0 );
require( overridenValue != overridenBonusValue);
overridenBonusValue = overridenValue;
return true;
}
/**
* @dev public function that is used to determine the current rate for token / ETH conversion
* @dev there exists a case where rate cant be set to 0, which is fine.
* @return The current token rate
*/
function getRate() public view returns(uint256) {
require( priceOfEMLTokenInUSDPenny !=0 );
require( priceOfEthInUSD !=0 );
uint256 rate;
if(overridenBonusValue > 0){
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100);
} else {
if (now <= (startTime + 1 days)) {
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100);
} if (now > (startTime + 1 days) && now <= (startTime + 2 days)) {
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent2.add(100)).div(100);
} else {
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent3.add(100)).div(100);
}
}
return rate;
}
/** @dev Initialise the Crowdsale contract.
* (can be removed for testing) _startTime Unix timestamp for the start of the token sale
* (can be removed for testing) _endTime Unix timestamp for the end of the token sale
* @param _multisigWallet Ethereum address to which the invested funds are forwarded
* @param _token Address of the token that will be rewarded for the investors
* @param _list contains a list of investors who completed KYC procedures.
*/
constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_multisigWallet != address(0));
require(_token != address(0));
require(_list != address(0));
startTime = _startTime;
endTime = _endTime;
multisigWallet = _multisigWallet;
owner = msg.sender;
token = EmalToken(_token);
list = EmalWhitelist(_list);
hardCap = token.getCrowdsaleAmount();
}
/** @dev Fallback function that can be used to buy EML tokens. Or in
* case of the owner, return ether to allow refunds in case crowdsale
* ended or paused and didnt reach soft_cap.
*/
function() external payable {
if (msg.sender == multisigWallet) {
require( (!isCrowdsaleActive()) && totalTokensSoldandAllocated<soft_cap);
} else {
if (list.isWhitelisted(msg.sender)) {
buyTokensUsingEther(msg.sender);
} else {
revert();
}
}
}
/** @dev Function for buying EML tokens using ether
* @param _investorAddr The address that should receive bought tokens
*/
function buyTokensUsingEther(address _investorAddr) internal whenNotPaused {
require(_investorAddr != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 returnToSender = 0;
// final rate after including rate value and bonus amount.
uint256 finalConversionRate = getRate();
// Calculate EML token amount to be transferred
uint256 tokens = weiAmount.mul(finalConversionRate);
// Distribute only the remaining tokens if final contribution exceeds hard cap
if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
tokens = hardCap.sub(totalTokensSoldandAllocated);
weiAmount = tokens.div(finalConversionRate);
returnToSender = msg.value.sub(weiAmount);
}
// update state and balances
etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount);
tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens);
totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens);
totalEtherRaisedByCrowdsale = totalEtherRaisedByCrowdsale.add(weiAmount);
totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);
// assert implies it should never fail
assert(token.transferFrom(owner, _investorAddr, tokens));
emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens);
// Forward funds
multisigWallet.transfer(weiAmount);
// Update token contract.
_postValidationUpdateTokenContract();
// Return funds that are over hard cap
if (returnToSender > 0) {
msg.sender.transfer(returnToSender);
}
}
function _postValidationUpdateTokenContract() internal {
/** @dev If hard cap is reachde allow token transfers after two weeks
* @dev Allow users to transfer tokens only after hardCap is reached
* @dev Notiy token contract about startTime to start transfers
*/
if (totalTokensSoldandAllocated == hardCap) {
token.setStartTimeForTokenTransfers(now + 2 weeks);
}
/** @dev If its the first token sold or allocated then set s, allow after 2 weeks
* @dev Allow users to transfer tokens only after ICO crowdsale ends.
* @dev Notify token contract about sale end time
*/
if (!isStartTimeSetForTokenTransfers) {
isStartTimeSetForTokenTransfers = true;
token.setStartTimeForTokenTransfers(endTime + 2 weeks);
}
}
/** @dev Internal function that is used to check if the incoming purchase should be accepted.
* @return True if the transaction can buy tokens
*/
function validPurchase() internal view returns(bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool minimumPurchase = msg.value >= 1*(10**18);
bool hardCapNotReached = totalTokensSoldandAllocated < hardCap;
return withinPeriod && hardCapNotReached && minimumPurchase;
}
/** @dev Public function to check if Crowdsale isActive or not
* @return True if Crowdsale event has ended
*/
function isCrowdsaleActive() public view returns(bool) {
if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){
return true;
} else {
return false;
}
}
/** @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) {
require(_owner != address(0));
return etherInvestments[_owner];
}
function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) {
require(_owner != address(0));
return tokensSoldForEther[_owner];
}
/** @dev Returns ether to token holders in case soft cap is not reached.
*/
function claimRefund() public whenNotPaused onlyOwner {
require(now>endTime);
require(totalTokensSoldandAllocated<soft_cap);
uint256 amount = etherInvestments[msg.sender];
if (address(this).balance >= amount) {
etherInvestments[msg.sender] = 0;
if (amount > 0) {
msg.sender.transfer(amount);
emit Refund(msg.sender, amount);
}
}
}
/** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC.
* functions are automatically called by ICO Sails.js app.
*/
/** @dev Allocates EML tokens to an investor address called automatically
* after receiving fiat or btc investments from KYC whitelisted investors.
* @param beneficiary The address of the investor
* @param tokenCount The number of tokens to be allocated to this address
*/
function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {
require(beneficiary != address(0));
require(validAllocation(tokenCount));
uint256 tokens = tokenCount;
/* Allocate only the remaining tokens if final contribution exceeds hard cap */
if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
tokens = hardCap.sub(totalTokensSoldandAllocated);
}
/* Update state and balances */
allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens);
totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);
totalTokensAllocated = totalTokensAllocated.add(tokens);
// assert implies it should never fail
assert(token.transferFrom(owner, beneficiary, tokens));
emit TokensAllocated(beneficiary, tokens);
/* Update token contract. */
_postValidationUpdateTokenContract();
return true;
}
function validAllocation( uint256 tokenCount ) internal view returns(bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool positiveAllocation = tokenCount > 0;
bool hardCapNotReached = totalTokensSoldandAllocated < hardCap;
return withinPeriod && positiveAllocation && hardCapNotReached;
}
/** @dev Getter function to check the amount of allocated tokens
* @param beneficiary address of the investor
*/
function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) {
require(beneficiary != address(0));
return allocatedTokens[beneficiary];
}
function getSoldandAllocatedTokens(address _addr) public view returns (uint256) {
require(_addr != address(0));
uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr));
return totalTokenCount;
}
}
pragma solidity 0.4.24;
import "./SafeMath.sol";
import "./Ownable.sol";
import "./Pausable.sol";
contract EmalToken {
// add function prototypes of only those used here
function transferFrom(address _from, address _to, uint256 _value) public returns(bool);
function getPresaleAmount() public view returns(uint256);
}
contract EmalWhitelist {
// add function prototypes of only those used here
function isWhitelisted(address investorAddr) public view returns(bool whitelisted);
}
contract EmalPresale is Ownable, Pausable {
using SafeMath for uint256;
// Start and end timestamps
uint256 public startTime;
uint256 public endTime;
// The token being sold
EmalToken public token;
// Whitelist contract used to store whitelisted addresses
EmalWhitelist public list;
// Address where funds are collected
address public multisigWallet;
// Hard cap in EMAL tokens
uint256 public hardCap;
// Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments.
uint256 public totalTokensSoldandAllocated = 0;
// Investor contributions made in ether
mapping(address => uint256) public etherInvestments;
// Tokens given to investors who sent ether investments
mapping(address => uint256) public tokensSoldForEther;
// Total ether raised by the Presale
uint256 public totalEtherRaisedByPresale = 0;
// Total number of tokens sold to investors who made payments in ether
uint256 public totalTokensSoldByEtherInvestments = 0;
// Count of allocated tokens for each investor or bounty user
mapping(address => uint256) public allocatedTokens;
// Count of total number of EML tokens that have been currently allocated to Presale investors
uint256 public totalTokensAllocated = 0;
/** @dev Event for EML token purchase using ether
* @param investorAddr Address that paid and got the tokens
* @param paidAmount The amount that was paid (in wei)
* @param tokenCount The amount of tokens that were bought
*/
event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount);
/** @dev Event fired when EML tokens are allocated to an investor account
* @param beneficiary Address that is allocated tokens
* @param tokenCount The amount of tokens that were allocated
*/
event TokensAllocated(address indexed beneficiary, uint256 tokenCount);
event TokensDeallocated(address indexed beneficiary, uint256 tokenCount);
/** @dev variables and functions which determine conversion rate from ETH to EML
* based on bonuses and current timestamp.
*/
uint256 priceOfEthInUSD = 450;
uint256 bonusPercent1 = 35;
uint256 priceOfEMLTokenInUSDPenny = 60;
uint256 overridenBonusValue = 0;
function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) {
require( overridenValue > 0 );
require( overridenValue != priceOfEthInUSD);
priceOfEthInUSD = overridenValue;
return true;
}
function getExchangeRate() public view returns(uint256){
return priceOfEthInUSD;
}
function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) {
require( overridenValue > 0 );
require( overridenValue != overridenBonusValue);
overridenBonusValue = overridenValue;
return true;
}
/** @dev public function that is used to determine the current rate for ETH to EML conversion
* @return The current token rate
*/
function getRate() public view returns(uint256) {
require(priceOfEMLTokenInUSDPenny > 0 );
require(priceOfEthInUSD > 0 );
uint256 rate;
if(overridenBonusValue > 0){
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100);
} else {
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100);
}
return rate;
}
/** @dev Initialise the Presale contract.
* (can be removed for testing) _startTime Unix timestamp for the start of the token sale
* (can be removed for testing) _endTime Unix timestamp for the end of the token sale
* @param _multisigWallet Ethereum address to which the invested funds are forwarded
* @param _token Address of the token that will be rewarded for the investors
* @param _list contains a list of investors who completed KYC procedures.
*/
constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_multisigWallet != address(0));
require(_token != address(0));
require(_list != address(0));
startTime = _startTime;
endTime = _endTime;
multisigWallet = _multisigWallet;
owner = msg.sender;
token = EmalToken(_token);
list = EmalWhitelist(_list);
hardCap = token.getPresaleAmount();
}
/** @dev Fallback function that can be used to buy tokens.
*/
function() external payable {
if (list.isWhitelisted(msg.sender)) {
buyTokensUsingEther(msg.sender);
} else {
/* Do not accept ETH */
revert();
}
}
/** @dev Function for buying EML tokens using ether
* @param _investorAddr The address that should receive bought tokens
*/
function buyTokensUsingEther(address _investorAddr) internal whenNotPaused {
require(_investorAddr != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 returnToSender = 0;
// final rate after including rate value and bonus amount.
uint256 finalConversionRate = getRate();
// Calculate EML token amount to be transferred
uint256 tokens = weiAmount.mul(finalConversionRate);
// Distribute only the remaining tokens if final contribution exceeds hard cap
if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
tokens = hardCap.sub(totalTokensSoldandAllocated);
weiAmount = tokens.div(finalConversionRate);
returnToSender = msg.value.sub(weiAmount);
}
// update state and balances
etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount);
tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens);
totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens);
totalEtherRaisedByPresale = totalEtherRaisedByPresale.add(weiAmount);
totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);
// assert implies it should never fail
assert(token.transferFrom(owner, _investorAddr, tokens));
emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens);
// Forward funds
multisigWallet.transfer(weiAmount);
// Return funds that are over hard cap
if (returnToSender > 0) {
msg.sender.transfer(returnToSender);
}
}
/**
* @dev Internal function that is used to check if the incoming purchase should be accepted.
* @return True if the transaction can buy tokens
*/
function validPurchase() internal view returns(bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool minimumPurchase = msg.value >= 1*(10**18);
bool hardCapNotReached = totalTokensSoldandAllocated < hardCap;
return withinPeriod && hardCapNotReached && minimumPurchase;
}
/** @dev Public function to check if Presale isActive or not
* @return True if Presale event has ended
*/
function isPresaleActive() public view returns(bool) {
if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){
return true;
} else {
return false;
}
}
/** @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) {
require(_owner != address(0));
return etherInvestments[_owner];
}
function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) {
require(_owner != address(0));
return tokensSoldForEther[_owner];
}
/** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC.
* functions are automatically called by ICO Sails.js app.
*/
/** @dev Allocates EML tokens to an investor address called automatically
* after receiving fiat or btc investments from KYC whitelisted investors.
* @param beneficiary The address of the investor
* @param tokenCount The number of tokens to be allocated to this address
*/
function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {
require(beneficiary != address(0));
require(validAllocation(tokenCount));
uint256 tokens = tokenCount;
/* Allocate only the remaining tokens if final contribution exceeds hard cap */
if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
tokens = hardCap.sub(totalTokensSoldandAllocated);
}
/* Update state and balances */
allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens);
totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);
totalTokensAllocated = totalTokensAllocated.add(tokens);
// assert implies it should never fail
assert(token.transferFrom(owner, beneficiary, tokens));
emit TokensAllocated(beneficiary, tokens);
return true;
}
function validAllocation( uint256 tokenCount ) internal view returns(bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool positiveAllocation = tokenCount > 0;
bool hardCapNotReached = totalTokensSoldandAllocated < hardCap;
return withinPeriod && positiveAllocation && hardCapNotReached;
}
/** @dev Getter function to check the amount of allocated tokens
* @param beneficiary address of the investor
*/
function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) {
require(beneficiary != address(0));
return allocatedTokens[beneficiary];
}
function getSoldandAllocatedTokens(address _addr) public view returns (uint256) {
require(_addr != address(0));
uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr));
return totalTokenCount;
}
}
pragma solidity 0.4.24;
import "./SafeMath.sol";
import './StandardToken.sol';
import './Ownable.sol';
contract EmalToken is StandardToken, Ownable {
using SafeMath for uint256;
string public constant symbol = "EML";
string public constant name = "e-Mal Token";
uint8 public constant decimals = 18;
// Total Number of tokens ever goint to be minted. 1 BILLION EML tokens.
uint256 private constant minting_capped_amount = 1000000000 * 10 ** uint256(decimals);
// 24% of initial supply
uint256 constant presale_amount = 120000000 * 10 ** uint256(decimals);
// 60% of inital supply
uint256 constant crowdsale_amount = 300000000 * 10 ** uint256(decimals);
// 8% of inital supply.
uint256 constant vesting_amount = 40000000 * 10 ** uint256(decimals);
// 8% of inital supply.
uint256 constant bounty_amount = 40000000 * 10 ** uint256(decimals);
uint256 private initialSupply = minting_capped_amount;
address public presaleAddress;
address public crowdsaleAddress;
address public vestingAddress;
address public bountyAddress;
/** @dev Defines the start time after which transferring of EML tokens
* will be allowed done so as to prevent early buyers from clearing out
* of their EML balance during the presale and publicsale.
*/
uint256 public startTimeForTransfers;
/** @dev to cap the total number of tokens that will ever be newly minted
* owner has to stop the minting by setting this variable to true.
*/
bool public mintingFinished = false;
/** @dev Miniting Essentials functions as per OpenZeppelin standards
*/
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/** @dev to prevent malicious use of EML tokens and to comply with Anti
* Money laundering regulations EML tokens can be frozen.
*/
mapping (address => bool) public frozenAccount;
/** @dev This generates a public event on the blockchain that will notify clients
*/
event FrozenFunds(address target, bool frozen);
event Mint(address indexed to, uint256 amount);
event MintFinished();
event Burn(address indexed burner, uint256 value);
constructor() public {
startTimeForTransfers = now - 210 days;
_totalSupply = initialSupply;
owner = msg.sender;
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, balances[owner]);
}
/* Do not accept ETH */
function() public payable {
revert();
}
/** @dev Basic setters and getters to allocate tokens for vesting factory, presale
* crowdsale and bounty this is done so that no need of actually transferring EML
* tokens to sale contracts and hence preventing EML tokens from the risk of being
* locked out in future inside the subcontracts.
*/
function setPresaleAddress(address _presaleAddress) external onlyOwner {
presaleAddress = _presaleAddress;
assert(approve(presaleAddress, presale_amount));
}
function setCrowdsaleAddress(address _crowdsaleAddress) external onlyOwner {
crowdsaleAddress = _crowdsaleAddress;
assert(approve(crowdsaleAddress, crowdsale_amount));
}
function setVestingAddress(address _vestingAddress) external onlyOwner {
vestingAddress = _vestingAddress;
assert(approve(vestingAddress, vesting_amount));
}
function setBountyAddress(address _bountyAddress) external onlyOwner {
bountyAddress = _bountyAddress;
assert(approve(bountyAddress, bounty_amount));
}
function getPresaleAmount() internal pure returns(uint256) {
return presale_amount;
}
function getCrowdsaleAmount() internal pure returns(uint256) {
return crowdsale_amount;
}
function getVestingAmount() internal pure returns(uint256) {
return vesting_amount;
}
function getBountyAmount() internal pure returns(uint256) {
return bounty_amount;
}
/** @dev Sets the start time after which transferring of EML tokens
* will be allowed done so as to prevent early buyers from clearing out
* of their EML balance during the presale and publicsale.
*/
function setStartTimeForTokenTransfers(uint256 _startTimeForTransfers) external {
require(msg.sender == crowdsaleAddress);
if (_startTimeForTransfers < startTimeForTransfers) {
startTimeForTransfers = _startTimeForTransfers;
}
}
/** @dev Transfer possible only after ICO ends and Frozen accounts
* wont be able to transfer funds to other any other account and viz.
* @notice added safeTransfer functionality
*/
function transfer(address _to, uint256 _value) public returns(bool) {
require(now >= startTimeForTransfers);
require(!frozenAccount[msg.sender]);
require(!frozenAccount[_to]);
require(super.transfer(_to, _value));
return true;
}
/** @dev Only owner's tokens can be transferred before Crowdsale ends.
* beacuse the inital supply of EML is allocated to owners acc and later
* distributed to various subcontracts.
* @notice added safeTransferFrom functionality
*/
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if (now < startTimeForTransfers) {
require(_from == owner);
}
require(super.transferFrom(_from, _to, _value));
return true;
}
/** @notice added safeApprove functionality
*/
function approve(address spender, uint256 tokens) public returns (bool){
require(super.approve(spender, tokens));
return true;
}
/** @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
* @param target Address to be frozen
* @param freeze either to freeze it or not
*/
function freezeAccount(address target, bool freeze) public onlyOwner {
require(frozenAccount[target] != freeze);
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
/** @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) public hasMintPermission canMint returns (bool) {
require(_totalSupply.add(_amount) <= minting_capped_amount);
_totalSupply = _totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/** @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
/** @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
_totalSupply = _totalSupply.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
pragma solidity 0.4.24;
import "./EmalToken.sol";
import "./SafeMath.sol";
import "./Ownable.sol";
/** @title StandardTokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner.
*/
contract StandardTokenVesting is Ownable {
using SafeMath for uint256;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/** @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
owner = msg.sender;
cliff = _start.add(_cliff);
start = _start;
}
/** @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(EmalToken token) public returns (bool){
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.transfer(beneficiary, unreleased);
emit Released(unreleased);
return true;
}
/** @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(EmalToken token) public onlyOwner returns(bool) {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.transfer(owner, refund);
emit Revoked();
return true;
}
/** @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(EmalToken token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/** @dev Calculates the amount that has already vested.
* @param token Emal token which is being vested
*/
function vestedAmount(EmalToken token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
pragma solidity 0.4.24;
import './Ownable.sol';
/** @notice This contract provides support for whitelisting addresses.
* only whitelisted addresses are allowed to send ether and buy tokens
* during preSale and Pulic crowdsale.
* @dev after deploying contract, deploy Presale / Crowdsale contract using
* EmalWhitelist address. To allow claim refund functionality and allow wallet
* owner efatoora to send ether to Crowdsale contract for refunds add wallet
* address to whitelist.
*/
contract EmalWhitelist is Ownable {
mapping(address => bool) whitelist;
event AddToWhitelist(address investorAddr);
event RemoveFromWhitelist(address investorAddr);
/** @dev Throws if operator is not whitelisted.
*/
modifier onlyIfWhitelisted(address investorAddr) {
require(whitelist[investorAddr]);
_;
}
constructor() public {
owner = msg.sender;
}
/** @dev Returns if an address is whitelisted or not
*/
function isWhitelisted(address investorAddr) public view returns(bool whitelisted) {
return whitelist[investorAddr];
}
/**
* @dev Adds an investor to whitelist
* @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements.
*/
function addToWhitelist(address investorAddr) public onlyOwner returns(bool success) {
require(investorAddr!= address(0));
whitelist[investorAddr] = true;
return true;
}
/**
* @dev Removes an investor's address from whitelist
* @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements.
*/
function removeFromWhitelist(address investorAddr) public onlyOwner returns(bool success) {
require(investorAddr!= address(0));
whitelist[investorAddr] = false;
return true;
}
}
pragma solidity 0.4.24;
contract ERC20Token {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint256 tokens) public returns (bool success);
function approve(address spender, uint256 tokens) public returns (bool success);
function transferFrom(address from, address to, uint256 tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
pragma solidity 0.4.24;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
pragma solidity 0.4.24;
import "./Ownable.sol";
/* Pausable contract */
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/** @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/** @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/** @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/** @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
pragma solidity 0.4.24;
/**
* @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;
}
}
pragma solidity 0.4.24;
import './ERC20Token.sol';
import './SafeMath.sol';
contract StandardToken is ERC20Token {
using SafeMath for uint256;
// Global variable to store total number of tokens passed from EmalToken.sol
uint256 _totalSupply;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address tokenOwner) public view returns (uint256){
return balances[tokenOwner];
}
function transfer(address to, uint256 tokens) public returns (bool){
require(to != address(0));
require(tokens > 0 && tokens <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// Transfer tokens from one address to another
function transferFrom(address from, address to, uint256 tokens) public returns (bool success){
require(to != address(0));
require(tokens > 0 && tokens <= balances[from]);
require(tokens <= allowed[from][msg.sender]);
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
emit Transfer(from, to, tokens);
return true;
}
// Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
function approve(address spender, uint256 tokens) public returns (bool success){
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// Function to check the amount of tokens that an owner allowed to a spender.
function allowance(address tokenOwner, address spender) public view returns (uint256 remaining){
return allowed[tokenOwner][spender];
}
// Increase the amount of tokens that an owner allowed to a spender.
// approve should be called when allowed[spender] == 0.
// To increment allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined)
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;
}
// Decrease the amount of tokens that an owner allowed to a spender.
// approve should be called when allowed[spender] == 0.
// To decrement allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined)
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;
}
}
pragma solidity 0.4.24;
import "./EmalToken.sol";
import "./SafeMath.sol";
import "./Ownable.sol";
/** @title StandardTokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner.
*/
contract StandardTokenVesting is Ownable {
using SafeMath for uint256;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/** @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
owner = msg.sender;
cliff = _start.add(_cliff);
start = _start;
}
/** @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(EmalToken token) public returns (bool){
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.transfer(beneficiary, unreleased);
emit Released(unreleased);
return true;
}
/** @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(EmalToken token) public onlyOwner returns(bool) {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.transfer(owner, refund);
emit Revoked();
return true;
}
/** @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(EmalToken token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/** @dev Calculates the amount that has already vested.
* @param token Emal token which is being vested
*/
function vestedAmount(EmalToken token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
pragma solidity 0.4.24;
import "./SafeMath.sol";
import "./Ownable.sol";
contract EmalToken {
// add function prototypes of only those used here
function transferFrom(address _from, address _to, uint256 _value) public returns(bool);
function getBountyAmount() public view returns(uint256);
}
contract EmalBounty is Ownable {
using SafeMath for uint256;
// The token being sold
EmalToken public token;
// Bounty contract state Data structures
enum State {
Active,
Closed
}
// contains current state of bounty contract
State public state;
// Bounty limit in EMAL tokens
uint256 public bountyLimit;
// Count of total number of EML tokens that have been currently allocated to bounty users
uint256 public totalTokensAllocated = 0;
// Count of allocated tokens (not issued only allocated) for each bounty user
mapping(address => uint256) public allocatedTokens;
// Count of allocated tokens issued to each bounty user.
mapping(address => uint256) public amountOfAllocatedTokensGivenOut;
/** @dev Event fired when tokens are allocated to a bounty user account
* @param beneficiary Address that is allocated tokens
* @param tokenCount The amount of tokens that were allocated
*/
event TokensAllocated(address indexed beneficiary, uint256 tokenCount);
event TokensDeallocated(address indexed beneficiary, uint256 tokenCount);
/**
* @dev Event fired when EML tokens are sent to a bounty user
* @param beneficiary Address where the allocated tokens were sent
* @param tokenCount The amount of tokens that were sent
*/
event IssuedAllocatedTokens(address indexed beneficiary, uint256 tokenCount);
/** @param _token Address of the token that will be rewarded for the investors
*/
constructor(address _token) public {
require(_token != address(0));
owner = msg.sender;
token = EmalToken(_token);
state = State.Active;
bountyLimit = token.getBountyAmount();
}
/* Do not accept ETH */
function() external payable {
revert();
}
function closeBounty() public onlyOwner returns(bool){
require( state!=State.Closed );
state = State.Closed;
return true;
}
/** @dev Public function to check if bounty isActive or not
* @return True if Bounty event has ended
*/
function isBountyActive() public view returns(bool) {
if (state==State.Active && totalTokensAllocated<bountyLimit){
return true;
} else {
return false;
}
}
/** @dev Allocates tokens to a bounty user
* @param beneficiary The address of the bounty user
* @param tokenCount The number of tokens to be allocated to this address
*/
function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {
require(beneficiary != address(0));
require(validAllocation(tokenCount));
uint256 tokens = tokenCount;
/* Allocate only the remaining tokens if final contribution exceeds hard cap */
if (totalTokensAllocated.add(tokens) > bountyLimit) {
tokens = bountyLimit.sub(totalTokensAllocated);
}
/* Update state and balances */
allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens);
totalTokensAllocated = totalTokensAllocated.add(tokens);
emit TokensAllocated(beneficiary, tokens);
return true;
}
function validAllocation( uint256 tokenCount ) internal view returns(bool) {
bool isActive = state==State.Active;
bool positiveAllocation = tokenCount>0;
bool bountyLimitNotReached = totalTokensAllocated<bountyLimit;
return isActive && positiveAllocation && bountyLimitNotReached;
}
/** @dev Remove tokens from a bounty user's allocation.
* @dev Used in game based bounty allocation, automatically called from the Sails app
* @param beneficiary The address of the bounty user
* @param tokenCount The number of tokens to be deallocated to this address
*/
function deductAllocatedTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {
require(beneficiary != address(0));
require(tokenCount>0 && tokenCount<=allocatedTokens[beneficiary]);
allocatedTokens[beneficiary] = allocatedTokens[beneficiary].sub(tokenCount);
totalTokensAllocated = totalTokensAllocated.sub(tokenCount);
emit TokensDeallocated(beneficiary, tokenCount);
return true;
}
/** @dev Getter function to check the amount of allocated tokens
* @param beneficiary address of the investor or the bounty user
*/
function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) {
require(beneficiary != address(0));
return allocatedTokens[beneficiary];
}
/** @dev Bounty users will be issued EML Tokens by the sails api,
* @dev after the Bounty has ended to their address
* @param beneficiary address of the bounty user
*/
function issueTokensToAllocatedUsers(address beneficiary) public onlyOwner returns(bool success) {
require(beneficiary!=address(0));
require(allocatedTokens[beneficiary]>0);
uint256 tokensToSend = allocatedTokens[beneficiary];
allocatedTokens[beneficiary] = 0;
amountOfAllocatedTokensGivenOut[beneficiary] = amountOfAllocatedTokensGivenOut[beneficiary].add(tokensToSend);
assert(token.transferFrom(owner, beneficiary, tokensToSend));
emit IssuedAllocatedTokens(beneficiary, tokensToSend);
return true;
}
}
pragma solidity 0.4.24;
import "./SafeMath.sol";
import "./Ownable.sol";
import "./Pausable.sol";
contract EmalToken {
// add function prototypes of only those used here
function transferFrom(address _from, address _to, uint256 _value) public returns(bool);
function getCrowdsaleAmount() public view returns(uint256);
function setStartTimeForTokenTransfers(uint256 _startTime) external;
}
contract EmalWhitelist {
// add function prototypes of only those used here
function isWhitelisted(address investorAddr) public view returns(bool whitelisted);
}
contract EmalCrowdsale is Ownable, Pausable {
using SafeMath for uint256;
// Start and end timestamps
uint256 public startTime;
uint256 public endTime;
// The token being sold
EmalToken public token;
// Whitelist contract used to store whitelisted addresses
EmalWhitelist public list;
// Address where funds are collected
address public multisigWallet;
// Switched to true once token contract is notified of when to enable token transfers
bool private isStartTimeSetForTokenTransfers = false;
// Hard cap in EMAL tokens
uint256 public hardCap;
// Soft cap in EMAL tokens
uint256 constant public soft_cap = 50000000 * (10 ** 18);
// Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments.
uint256 public totalTokensSoldandAllocated = 0;
// Investor contributions made in ether
mapping(address => uint256) public etherInvestments;
// Tokens given to investors who sent ether investments
mapping(address => uint256) public tokensSoldForEther;
// Total ether raised by the Crowdsale
uint256 public totalEtherRaisedByCrowdsale = 0;
// Total number of tokens sold to investors who made payments in ether
uint256 public totalTokensSoldByEtherInvestments = 0;
// Count of allocated tokens for each investor or bounty user
mapping(address => uint256) public allocatedTokens;
// Count of total number of EML tokens that have been currently allocated to Crowdsale investors
uint256 public totalTokensAllocated = 0;
/** @dev Event for EML token purchase using ether
* @param investorAddr Address that paid and got the tokens
* @param paidAmount The amount that was paid (in wei)
* @param tokenCount The amount of tokens that were bought
*/
event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount);
/**
* @dev Event for refund logging
* @param receiver The address that received the refund
* @param amount The amount that is being refunded (in wei)
*/
event Refund(address indexed receiver, uint256 amount);
/** @dev Event fired when EML tokens are allocated to an investor account
* @param beneficiary Address that is allocated tokens
* @param tokenCount The amount of tokens that were allocated
*/
event TokensAllocated(address indexed beneficiary, uint256 tokenCount);
event TokensDeallocated(address indexed beneficiary, uint256 tokenCount);
/** @dev variables and functions which determine conversion rate from ETH to EML
* based on bonuses and current timestamp.
*/
uint256 priceOfEthInUSD = 450;
uint256 bonusPercent1 = 25;
uint256 bonusPercent2 = 15;
uint256 bonusPercent3 = 0;
uint256 priceOfEMLTokenInUSDPenny = 60;
uint256 overridenBonusValue = 0;
function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) {
require( overridenValue > 0 );
require( overridenValue != priceOfEthInUSD);
priceOfEthInUSD = overridenValue;
return true;
}
function getExchangeRate() public view returns(uint256){
return priceOfEthInUSD;
}
function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) {
require( overridenValue > 0 );
require( overridenValue != overridenBonusValue);
overridenBonusValue = overridenValue;
return true;
}
/**
* @dev public function that is used to determine the current rate for token / ETH conversion
* @dev there exists a case where rate cant be set to 0, which is fine.
* @return The current token rate
*/
function getRate() public view returns(uint256) {
require( priceOfEMLTokenInUSDPenny !=0 );
require( priceOfEthInUSD !=0 );
uint256 rate;
if(overridenBonusValue > 0){
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100);
} else {
if (now <= (startTime + 1 days)) {
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100);
} if (now > (startTime + 1 days) && now <= (startTime + 2 days)) {
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent2.add(100)).div(100);
} else {
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent3.add(100)).div(100);
}
}
return rate;
}
/** @dev Initialise the Crowdsale contract.
* (can be removed for testing) _startTime Unix timestamp for the start of the token sale
* (can be removed for testing) _endTime Unix timestamp for the end of the token sale
* @param _multisigWallet Ethereum address to which the invested funds are forwarded
* @param _token Address of the token that will be rewarded for the investors
* @param _list contains a list of investors who completed KYC procedures.
*/
constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_multisigWallet != address(0));
require(_token != address(0));
require(_list != address(0));
startTime = _startTime;
endTime = _endTime;
multisigWallet = _multisigWallet;
owner = msg.sender;
token = EmalToken(_token);
list = EmalWhitelist(_list);
hardCap = token.getCrowdsaleAmount();
}
/** @dev Fallback function that can be used to buy EML tokens. Or in
* case of the owner, return ether to allow refunds in case crowdsale
* ended or paused and didnt reach soft_cap.
*/
function() external payable {
if (msg.sender == multisigWallet) {
require( (!isCrowdsaleActive()) && totalTokensSoldandAllocated<soft_cap);
} else {
if (list.isWhitelisted(msg.sender)) {
buyTokensUsingEther(msg.sender);
} else {
revert();
}
}
}
/** @dev Function for buying EML tokens using ether
* @param _investorAddr The address that should receive bought tokens
*/
function buyTokensUsingEther(address _investorAddr) internal whenNotPaused {
require(_investorAddr != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 returnToSender = 0;
// final rate after including rate value and bonus amount.
uint256 finalConversionRate = getRate();
// Calculate EML token amount to be transferred
uint256 tokens = weiAmount.mul(finalConversionRate);
// Distribute only the remaining tokens if final contribution exceeds hard cap
if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
tokens = hardCap.sub(totalTokensSoldandAllocated);
weiAmount = tokens.div(finalConversionRate);
returnToSender = msg.value.sub(weiAmount);
}
// update state and balances
etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount);
tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens);
totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens);
totalEtherRaisedByCrowdsale = totalEtherRaisedByCrowdsale.add(weiAmount);
totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);
// assert implies it should never fail
assert(token.transferFrom(owner, _investorAddr, tokens));
emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens);
// Forward funds
multisigWallet.transfer(weiAmount);
// Update token contract.
_postValidationUpdateTokenContract();
// Return funds that are over hard cap
if (returnToSender > 0) {
msg.sender.transfer(returnToSender);
}
}
function _postValidationUpdateTokenContract() internal {
/** @dev If hard cap is reachde allow token transfers after two weeks
* @dev Allow users to transfer tokens only after hardCap is reached
* @dev Notiy token contract about startTime to start transfers
*/
if (totalTokensSoldandAllocated == hardCap) {
token.setStartTimeForTokenTransfers(now + 2 weeks);
}
/** @dev If its the first token sold or allocated then set s, allow after 2 weeks
* @dev Allow users to transfer tokens only after ICO crowdsale ends.
* @dev Notify token contract about sale end time
*/
if (!isStartTimeSetForTokenTransfers) {
isStartTimeSetForTokenTransfers = true;
token.setStartTimeForTokenTransfers(endTime + 2 weeks);
}
}
/** @dev Internal function that is used to check if the incoming purchase should be accepted.
* @return True if the transaction can buy tokens
*/
function validPurchase() internal view returns(bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool minimumPurchase = msg.value >= 1*(10**18);
bool hardCapNotReached = totalTokensSoldandAllocated < hardCap;
return withinPeriod && hardCapNotReached && minimumPurchase;
}
/** @dev Public function to check if Crowdsale isActive or not
* @return True if Crowdsale event has ended
*/
function isCrowdsaleActive() public view returns(bool) {
if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){
return true;
} else {
return false;
}
}
/** @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) {
require(_owner != address(0));
return etherInvestments[_owner];
}
function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) {
require(_owner != address(0));
return tokensSoldForEther[_owner];
}
/** @dev Returns ether to token holders in case soft cap is not reached.
*/
function claimRefund() public whenNotPaused onlyOwner {
require(now>endTime);
require(totalTokensSoldandAllocated<soft_cap);
uint256 amount = etherInvestments[msg.sender];
if (address(this).balance >= amount) {
etherInvestments[msg.sender] = 0;
if (amount > 0) {
msg.sender.transfer(amount);
emit Refund(msg.sender, amount);
}
}
}
/** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC.
* functions are automatically called by ICO Sails.js app.
*/
/** @dev Allocates EML tokens to an investor address called automatically
* after receiving fiat or btc investments from KYC whitelisted investors.
* @param beneficiary The address of the investor
* @param tokenCount The number of tokens to be allocated to this address
*/
function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {
require(beneficiary != address(0));
require(validAllocation(tokenCount));
uint256 tokens = tokenCount;
/* Allocate only the remaining tokens if final contribution exceeds hard cap */
if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
tokens = hardCap.sub(totalTokensSoldandAllocated);
}
/* Update state and balances */
allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens);
totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);
totalTokensAllocated = totalTokensAllocated.add(tokens);
// assert implies it should never fail
assert(token.transferFrom(owner, beneficiary, tokens));
emit TokensAllocated(beneficiary, tokens);
/* Update token contract. */
_postValidationUpdateTokenContract();
return true;
}
function validAllocation( uint256 tokenCount ) internal view returns(bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool positiveAllocation = tokenCount > 0;
bool hardCapNotReached = totalTokensSoldandAllocated < hardCap;
return withinPeriod && positiveAllocation && hardCapNotReached;
}
/** @dev Getter function to check the amount of allocated tokens
* @param beneficiary address of the investor
*/
function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) {
require(beneficiary != address(0));
return allocatedTokens[beneficiary];
}
function getSoldandAllocatedTokens(address _addr) public view returns (uint256) {
require(_addr != address(0));
uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr));
return totalTokenCount;
}
}
pragma solidity 0.4.24;
import "./SafeMath.sol";
import "./Ownable.sol";
import "./Pausable.sol";
contract EmalToken {
// add function prototypes of only those used here
function transferFrom(address _from, address _to, uint256 _value) public returns(bool);
function getPresaleAmount() public view returns(uint256);
}
contract EmalWhitelist {
// add function prototypes of only those used here
function isWhitelisted(address investorAddr) public view returns(bool whitelisted);
}
contract EmalPresale is Ownable, Pausable {
using SafeMath for uint256;
// Start and end timestamps
uint256 public startTime;
uint256 public endTime;
// The token being sold
EmalToken public token;
// Whitelist contract used to store whitelisted addresses
EmalWhitelist public list;
// Address where funds are collected
address public multisigWallet;
// Hard cap in EMAL tokens
uint256 public hardCap;
// Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments.
uint256 public totalTokensSoldandAllocated = 0;
// Investor contributions made in ether
mapping(address => uint256) public etherInvestments;
// Tokens given to investors who sent ether investments
mapping(address => uint256) public tokensSoldForEther;
// Total ether raised by the Presale
uint256 public totalEtherRaisedByPresale = 0;
// Total number of tokens sold to investors who made payments in ether
uint256 public totalTokensSoldByEtherInvestments = 0;
// Count of allocated tokens for each investor or bounty user
mapping(address => uint256) public allocatedTokens;
// Count of total number of EML tokens that have been currently allocated to Presale investors
uint256 public totalTokensAllocated = 0;
/** @dev Event for EML token purchase using ether
* @param investorAddr Address that paid and got the tokens
* @param paidAmount The amount that was paid (in wei)
* @param tokenCount The amount of tokens that were bought
*/
event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount);
/** @dev Event fired when EML tokens are allocated to an investor account
* @param beneficiary Address that is allocated tokens
* @param tokenCount The amount of tokens that were allocated
*/
event TokensAllocated(address indexed beneficiary, uint256 tokenCount);
event TokensDeallocated(address indexed beneficiary, uint256 tokenCount);
/** @dev variables and functions which determine conversion rate from ETH to EML
* based on bonuses and current timestamp.
*/
uint256 priceOfEthInUSD = 450;
uint256 bonusPercent1 = 35;
uint256 priceOfEMLTokenInUSDPenny = 60;
uint256 overridenBonusValue = 0;
function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) {
require( overridenValue > 0 );
require( overridenValue != priceOfEthInUSD);
priceOfEthInUSD = overridenValue;
return true;
}
function getExchangeRate() public view returns(uint256){
return priceOfEthInUSD;
}
function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) {
require( overridenValue > 0 );
require( overridenValue != overridenBonusValue);
overridenBonusValue = overridenValue;
return true;
}
/** @dev public function that is used to determine the current rate for ETH to EML conversion
* @return The current token rate
*/
function getRate() public view returns(uint256) {
require(priceOfEMLTokenInUSDPenny > 0 );
require(priceOfEthInUSD > 0 );
uint256 rate;
if(overridenBonusValue > 0){
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100);
} else {
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100);
}
return rate;
}
/** @dev Initialise the Presale contract.
* (can be removed for testing) _startTime Unix timestamp for the start of the token sale
* (can be removed for testing) _endTime Unix timestamp for the end of the token sale
* @param _multisigWallet Ethereum address to which the invested funds are forwarded
* @param _token Address of the token that will be rewarded for the investors
* @param _list contains a list of investors who completed KYC procedures.
*/
constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_multisigWallet != address(0));
require(_token != address(0));
require(_list != address(0));
startTime = _startTime;
endTime = _endTime;
multisigWallet = _multisigWallet;
owner = msg.sender;
token = EmalToken(_token);
list = EmalWhitelist(_list);
hardCap = token.getPresaleAmount();
}
/** @dev Fallback function that can be used to buy tokens.
*/
function() external payable {
if (list.isWhitelisted(msg.sender)) {
buyTokensUsingEther(msg.sender);
} else {
/* Do not accept ETH */
revert();
}
}
/** @dev Function for buying EML tokens using ether
* @param _investorAddr The address that should receive bought tokens
*/
function buyTokensUsingEther(address _investorAddr) internal whenNotPaused {
require(_investorAddr != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 returnToSender = 0;
// final rate after including rate value and bonus amount.
uint256 finalConversionRate = getRate();
// Calculate EML token amount to be transferred
uint256 tokens = weiAmount.mul(finalConversionRate);
// Distribute only the remaining tokens if final contribution exceeds hard cap
if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
tokens = hardCap.sub(totalTokensSoldandAllocated);
weiAmount = tokens.div(finalConversionRate);
returnToSender = msg.value.sub(weiAmount);
}
// update state and balances
etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount);
tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens);
totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens);
totalEtherRaisedByPresale = totalEtherRaisedByPresale.add(weiAmount);
totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);
// assert implies it should never fail
assert(token.transferFrom(owner, _investorAddr, tokens));
emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens);
// Forward funds
multisigWallet.transfer(weiAmount);
// Return funds that are over hard cap
if (returnToSender > 0) {
msg.sender.transfer(returnToSender);
}
}
/**
* @dev Internal function that is used to check if the incoming purchase should be accepted.
* @return True if the transaction can buy tokens
*/
function validPurchase() internal view returns(bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool minimumPurchase = msg.value >= 1*(10**18);
bool hardCapNotReached = totalTokensSoldandAllocated < hardCap;
return withinPeriod && hardCapNotReached && minimumPurchase;
}
/** @dev Public function to check if Presale isActive or not
* @return True if Presale event has ended
*/
function isPresaleActive() public view returns(bool) {
if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){
return true;
} else {
return false;
}
}
/** @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) {
require(_owner != address(0));
return etherInvestments[_owner];
}
function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) {
require(_owner != address(0));
return tokensSoldForEther[_owner];
}
/** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC.
* functions are automatically called by ICO Sails.js app.
*/
/** @dev Allocates EML tokens to an investor address called automatically
* after receiving fiat or btc investments from KYC whitelisted investors.
* @param beneficiary The address of the investor
* @param tokenCount The number of tokens to be allocated to this address
*/
function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {
require(beneficiary != address(0));
require(validAllocation(tokenCount));
uint256 tokens = tokenCount;
/* Allocate only the remaining tokens if final contribution exceeds hard cap */
if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
tokens = hardCap.sub(totalTokensSoldandAllocated);
}
/* Update state and balances */
allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens);
totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);
totalTokensAllocated = totalTokensAllocated.add(tokens);
// assert implies it should never fail
assert(token.transferFrom(owner, beneficiary, tokens));
emit TokensAllocated(beneficiary, tokens);
return true;
}
function validAllocation( uint256 tokenCount ) internal view returns(bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool positiveAllocation = tokenCount > 0;
bool hardCapNotReached = totalTokensSoldandAllocated < hardCap;
return withinPeriod && positiveAllocation && hardCapNotReached;
}
/** @dev Getter function to check the amount of allocated tokens
* @param beneficiary address of the investor
*/
function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) {
require(beneficiary != address(0));
return allocatedTokens[beneficiary];
}
function getSoldandAllocatedTokens(address _addr) public view returns (uint256) {
require(_addr != address(0));
uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr));
return totalTokenCount;
}
}
pragma solidity 0.4.24;
import "./SafeMath.sol";
import './StandardToken.sol';
import './Ownable.sol';
contract EmalToken is StandardToken, Ownable {
using SafeMath for uint256;
string public constant symbol = "EML";
string public constant name = "e-Mal Token";
uint8 public constant decimals = 18;
// Total Number of tokens ever goint to be minted. 1 BILLION EML tokens.
uint256 private constant minting_capped_amount = 1000000000 * 10 ** uint256(decimals);
// 24% of initial supply
uint256 constant presale_amount = 120000000 * 10 ** uint256(decimals);
// 60% of inital supply
uint256 constant crowdsale_amount = 300000000 * 10 ** uint256(decimals);
// 8% of inital supply.
uint256 constant vesting_amount = 40000000 * 10 ** uint256(decimals);
// 8% of inital supply.
uint256 constant bounty_amount = 40000000 * 10 ** uint256(decimals);
uint256 private initialSupply = minting_capped_amount;
address public presaleAddress;
address public crowdsaleAddress;
address public vestingAddress;
address public bountyAddress;
/** @dev Defines the start time after which transferring of EML tokens
* will be allowed done so as to prevent early buyers from clearing out
* of their EML balance during the presale and publicsale.
*/
uint256 public startTimeForTransfers;
/** @dev to cap the total number of tokens that will ever be newly minted
* owner has to stop the minting by setting this variable to true.
*/
bool public mintingFinished = false;
/** @dev Miniting Essentials functions as per OpenZeppelin standards
*/
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/** @dev to prevent malicious use of EML tokens and to comply with Anti
* Money laundering regulations EML tokens can be frozen.
*/
mapping (address => bool) public frozenAccount;
/** @dev This generates a public event on the blockchain that will notify clients
*/
event FrozenFunds(address target, bool frozen);
event Mint(address indexed to, uint256 amount);
event MintFinished();
event Burn(address indexed burner, uint256 value);
constructor() public {
startTimeForTransfers = now - 210 days;
_totalSupply = initialSupply;
owner = msg.sender;
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, balances[owner]);
}
/* Do not accept ETH */
function() public payable {
revert();
}
/** @dev Basic setters and getters to allocate tokens for vesting factory, presale
* crowdsale and bounty this is done so that no need of actually transferring EML
* tokens to sale contracts and hence preventing EML tokens from the risk of being
* locked out in future inside the subcontracts.
*/
function setPresaleAddress(address _presaleAddress) external onlyOwner {
presaleAddress = _presaleAddress;
assert(approve(presaleAddress, presale_amount));
}
function setCrowdsaleAddress(address _crowdsaleAddress) external onlyOwner {
crowdsaleAddress = _crowdsaleAddress;
assert(approve(crowdsaleAddress, crowdsale_amount));
}
function setVestingAddress(address _vestingAddress) external onlyOwner {
vestingAddress = _vestingAddress;
assert(approve(vestingAddress, vesting_amount));
}
function setBountyAddress(address _bountyAddress) external onlyOwner {
bountyAddress = _bountyAddress;
assert(approve(bountyAddress, bounty_amount));
}
function getPresaleAmount() internal pure returns(uint256) {
return presale_amount;
}
function getCrowdsaleAmount() internal pure returns(uint256) {
return crowdsale_amount;
}
function getVestingAmount() internal pure returns(uint256) {
return vesting_amount;
}
function getBountyAmount() internal pure returns(uint256) {
return bounty_amount;
}
/** @dev Sets the start time after which transferring of EML tokens
* will be allowed done so as to prevent early buyers from clearing out
* of their EML balance during the presale and publicsale.
*/
function setStartTimeForTokenTransfers(uint256 _startTimeForTransfers) external {
require(msg.sender == crowdsaleAddress);
if (_startTimeForTransfers < startTimeForTransfers) {
startTimeForTransfers = _startTimeForTransfers;
}
}
/** @dev Transfer possible only after ICO ends and Frozen accounts
* wont be able to transfer funds to other any other account and viz.
* @notice added safeTransfer functionality
*/
function transfer(address _to, uint256 _value) public returns(bool) {
require(now >= startTimeForTransfers);
require(!frozenAccount[msg.sender]);
require(!frozenAccount[_to]);
require(super.transfer(_to, _value));
return true;
}
/** @dev Only owner's tokens can be transferred before Crowdsale ends.
* beacuse the inital supply of EML is allocated to owners acc and later
* distributed to various subcontracts.
* @notice added safeTransferFrom functionality
*/
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if (now < startTimeForTransfers) {
require(_from == owner);
}
require(super.transferFrom(_from, _to, _value));
return true;
}
/** @notice added safeApprove functionality
*/
function approve(address spender, uint256 tokens) public returns (bool){
require(super.approve(spender, tokens));
return true;
}
/** @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
* @param target Address to be frozen
* @param freeze either to freeze it or not
*/
function freezeAccount(address target, bool freeze) public onlyOwner {
require(frozenAccount[target] != freeze);
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
/** @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) public hasMintPermission canMint returns (bool) {
require(_totalSupply.add(_amount) <= minting_capped_amount);
_totalSupply = _totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/** @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
/** @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
_totalSupply = _totalSupply.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
pragma solidity 0.4.24;
import "./EmalToken.sol";
import "./SafeMath.sol";
import "./Ownable.sol";
/** @title StandardTokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner.
*/
contract StandardTokenVesting is Ownable {
using SafeMath for uint256;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/** @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
owner = msg.sender;
cliff = _start.add(_cliff);
start = _start;
}
/** @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(EmalToken token) public returns (bool){
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.transfer(beneficiary, unreleased);
emit Released(unreleased);
return true;
}
/** @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(EmalToken token) public onlyOwner returns(bool) {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.transfer(owner, refund);
emit Revoked();
return true;
}
/** @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(EmalToken token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/** @dev Calculates the amount that has already vested.
* @param token Emal token which is being vested
*/
function vestedAmount(EmalToken token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
pragma solidity 0.4.24;
import './Ownable.sol';
/** @notice This contract provides support for whitelisting addresses.
* only whitelisted addresses are allowed to send ether and buy tokens
* during preSale and Pulic crowdsale.
* @dev after deploying contract, deploy Presale / Crowdsale contract using
* EmalWhitelist address. To allow claim refund functionality and allow wallet
* owner efatoora to send ether to Crowdsale contract for refunds add wallet
* address to whitelist.
*/
contract EmalWhitelist is Ownable {
mapping(address => bool) whitelist;
event AddToWhitelist(address investorAddr);
event RemoveFromWhitelist(address investorAddr);
/** @dev Throws if operator is not whitelisted.
*/
modifier onlyIfWhitelisted(address investorAddr) {
require(whitelist[investorAddr]);
_;
}
constructor() public {
owner = msg.sender;
}
/** @dev Returns if an address is whitelisted or not
*/
function isWhitelisted(address investorAddr) public view returns(bool whitelisted) {
return whitelist[investorAddr];
}
/**
* @dev Adds an investor to whitelist
* @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements.
*/
function addToWhitelist(address investorAddr) public onlyOwner returns(bool success) {
require(investorAddr!= address(0));
whitelist[investorAddr] = true;
return true;
}
/**
* @dev Removes an investor's address from whitelist
* @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements.
*/
function removeFromWhitelist(address investorAddr) public onlyOwner returns(bool success) {
require(investorAddr!= address(0));
whitelist[investorAddr] = false;
return true;
}
}
pragma solidity 0.4.24;
contract ERC20Token {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint256 tokens) public returns (bool success);
function approve(address spender, uint256 tokens) public returns (bool success);
function transferFrom(address from, address to, uint256 tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
pragma solidity 0.4.24;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
pragma solidity 0.4.24;
import "./Ownable.sol";
/* Pausable contract */
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/** @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/** @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/** @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/** @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
pragma solidity 0.4.24;
/**
* @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;
}
}
pragma solidity 0.4.24;
import './ERC20Token.sol';
import './SafeMath.sol';
contract StandardToken is ERC20Token {
using SafeMath for uint256;
// Global variable to store total number of tokens passed from EmalToken.sol
uint256 _totalSupply;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address tokenOwner) public view returns (uint256){
return balances[tokenOwner];
}
function transfer(address to, uint256 tokens) public returns (bool){
require(to != address(0));
require(tokens > 0 && tokens <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// Transfer tokens from one address to another
function transferFrom(address from, address to, uint256 tokens) public returns (bool success){
require(to != address(0));
require(tokens > 0 && tokens <= balances[from]);
require(tokens <= allowed[from][msg.sender]);
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
emit Transfer(from, to, tokens);
return true;
}
// Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
function approve(address spender, uint256 tokens) public returns (bool success){
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// Function to check the amount of tokens that an owner allowed to a spender.
function allowance(address tokenOwner, address spender) public view returns (uint256 remaining){
return allowed[tokenOwner][spender];
}
// Increase the amount of tokens that an owner allowed to a spender.
// approve should be called when allowed[spender] == 0.
// To increment allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined)
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;
}
// Decrease the amount of tokens that an owner allowed to a spender.
// approve should be called when allowed[spender] == 0.
// To decrement allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined)
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;
}
}
pragma solidity 0.4.24;
import "./EmalToken.sol";
import "./SafeMath.sol";
import "./Ownable.sol";
/** @title StandardTokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner.
*/
contract StandardTokenVesting is Ownable {
using SafeMath for uint256;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/** @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
owner = msg.sender;
cliff = _start.add(_cliff);
start = _start;
}
/** @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(EmalToken token) public returns (bool){
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.transfer(beneficiary, unreleased);
emit Released(unreleased);
return true;
}
/** @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(EmalToken token) public onlyOwner returns(bool) {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.transfer(owner, refund);
emit Revoked();
return true;
}
/** @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(EmalToken token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/** @dev Calculates the amount that has already vested.
* @param token Emal token which is being vested
*/
function vestedAmount(EmalToken token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
pragma solidity 0.4.24;
import "./SafeMath.sol";
import "./Ownable.sol";
contract EmalToken {
// add function prototypes of only those used here
function transferFrom(address _from, address _to, uint256 _value) public returns(bool);
function getBountyAmount() public view returns(uint256);
}
contract EmalBounty is Ownable {
using SafeMath for uint256;
// The token being sold
EmalToken public token;
// Bounty contract state Data structures
enum State {
Active,
Closed
}
// contains current state of bounty contract
State public state;
// Bounty limit in EMAL tokens
uint256 public bountyLimit;
// Count of total number of EML tokens that have been currently allocated to bounty users
uint256 public totalTokensAllocated = 0;
// Count of allocated tokens (not issued only allocated) for each bounty user
mapping(address => uint256) public allocatedTokens;
// Count of allocated tokens issued to each bounty user.
mapping(address => uint256) public amountOfAllocatedTokensGivenOut;
/** @dev Event fired when tokens are allocated to a bounty user account
* @param beneficiary Address that is allocated tokens
* @param tokenCount The amount of tokens that were allocated
*/
event TokensAllocated(address indexed beneficiary, uint256 tokenCount);
event TokensDeallocated(address indexed beneficiary, uint256 tokenCount);
/**
* @dev Event fired when EML tokens are sent to a bounty user
* @param beneficiary Address where the allocated tokens were sent
* @param tokenCount The amount of tokens that were sent
*/
event IssuedAllocatedTokens(address indexed beneficiary, uint256 tokenCount);
/** @param _token Address of the token that will be rewarded for the investors
*/
constructor(address _token) public {
require(_token != address(0));
owner = msg.sender;
token = EmalToken(_token);
state = State.Active;
bountyLimit = token.getBountyAmount();
}
/* Do not accept ETH */
function() external payable {
revert();
}
function closeBounty() public onlyOwner returns(bool){
require( state!=State.Closed );
state = State.Closed;
return true;
}
/** @dev Public function to check if bounty isActive or not
* @return True if Bounty event has ended
*/
function isBountyActive() public view returns(bool) {
if (state==State.Active && totalTokensAllocated<bountyLimit){
return true;
} else {
return false;
}
}
/** @dev Allocates tokens to a bounty user
* @param beneficiary The address of the bounty user
* @param tokenCount The number of tokens to be allocated to this address
*/
function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {
require(beneficiary != address(0));
require(validAllocation(tokenCount));
uint256 tokens = tokenCount;
/* Allocate only the remaining tokens if final contribution exceeds hard cap */
if (totalTokensAllocated.add(tokens) > bountyLimit) {
tokens = bountyLimit.sub(totalTokensAllocated);
}
/* Update state and balances */
allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens);
totalTokensAllocated = totalTokensAllocated.add(tokens);
emit TokensAllocated(beneficiary, tokens);
return true;
}
function validAllocation( uint256 tokenCount ) internal view returns(bool) {
bool isActive = state==State.Active;
bool positiveAllocation = tokenCount>0;
bool bountyLimitNotReached = totalTokensAllocated<bountyLimit;
return isActive && positiveAllocation && bountyLimitNotReached;
}
/** @dev Remove tokens from a bounty user's allocation.
* @dev Used in game based bounty allocation, automatically called from the Sails app
* @param beneficiary The address of the bounty user
* @param tokenCount The number of tokens to be deallocated to this address
*/
function deductAllocatedTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {
require(beneficiary != address(0));
require(tokenCount>0 && tokenCount<=allocatedTokens[beneficiary]);
allocatedTokens[beneficiary] = allocatedTokens[beneficiary].sub(tokenCount);
totalTokensAllocated = totalTokensAllocated.sub(tokenCount);
emit TokensDeallocated(beneficiary, tokenCount);
return true;
}
/** @dev Getter function to check the amount of allocated tokens
* @param beneficiary address of the investor or the bounty user
*/
function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) {
require(beneficiary != address(0));
return allocatedTokens[beneficiary];
}
/** @dev Bounty users will be issued EML Tokens by the sails api,
* @dev after the Bounty has ended to their address
* @param beneficiary address of the bounty user
*/
function issueTokensToAllocatedUsers(address beneficiary) public onlyOwner returns(bool success) {
require(beneficiary!=address(0));
require(allocatedTokens[beneficiary]>0);
uint256 tokensToSend = allocatedTokens[beneficiary];
allocatedTokens[beneficiary] = 0;
amountOfAllocatedTokensGivenOut[beneficiary] = amountOfAllocatedTokensGivenOut[beneficiary].add(tokensToSend);
assert(token.transferFrom(owner, beneficiary, tokensToSend));
emit IssuedAllocatedTokens(beneficiary, tokensToSend);
return true;
}
}
pragma solidity 0.4.24;
import "./SafeMath.sol";
import "./Ownable.sol";
import "./Pausable.sol";
contract EmalToken {
// add function prototypes of only those used here
function transferFrom(address _from, address _to, uint256 _value) public returns(bool);
function getCrowdsaleAmount() public view returns(uint256);
function setStartTimeForTokenTransfers(uint256 _startTime) external;
}
contract EmalWhitelist {
// add function prototypes of only those used here
function isWhitelisted(address investorAddr) public view returns(bool whitelisted);
}
contract EmalCrowdsale is Ownable, Pausable {
using SafeMath for uint256;
// Start and end timestamps
uint256 public startTime;
uint256 public endTime;
// The token being sold
EmalToken public token;
// Whitelist contract used to store whitelisted addresses
EmalWhitelist public list;
// Address where funds are collected
address public multisigWallet;
// Switched to true once token contract is notified of when to enable token transfers
bool private isStartTimeSetForTokenTransfers = false;
// Hard cap in EMAL tokens
uint256 public hardCap;
// Soft cap in EMAL tokens
uint256 constant public soft_cap = 50000000 * (10 ** 18);
// Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments.
uint256 public totalTokensSoldandAllocated = 0;
// Investor contributions made in ether
mapping(address => uint256) public etherInvestments;
// Tokens given to investors who sent ether investments
mapping(address => uint256) public tokensSoldForEther;
// Total ether raised by the Crowdsale
uint256 public totalEtherRaisedByCrowdsale = 0;
// Total number of tokens sold to investors who made payments in ether
uint256 public totalTokensSoldByEtherInvestments = 0;
// Count of allocated tokens for each investor or bounty user
mapping(address => uint256) public allocatedTokens;
// Count of total number of EML tokens that have been currently allocated to Crowdsale investors
uint256 public totalTokensAllocated = 0;
/** @dev Event for EML token purchase using ether
* @param investorAddr Address that paid and got the tokens
* @param paidAmount The amount that was paid (in wei)
* @param tokenCount The amount of tokens that were bought
*/
event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount);
/**
* @dev Event for refund logging
* @param receiver The address that received the refund
* @param amount The amount that is being refunded (in wei)
*/
event Refund(address indexed receiver, uint256 amount);
/** @dev Event fired when EML tokens are allocated to an investor account
* @param beneficiary Address that is allocated tokens
* @param tokenCount The amount of tokens that were allocated
*/
event TokensAllocated(address indexed beneficiary, uint256 tokenCount);
event TokensDeallocated(address indexed beneficiary, uint256 tokenCount);
/** @dev variables and functions which determine conversion rate from ETH to EML
* based on bonuses and current timestamp.
*/
uint256 priceOfEthInUSD = 450;
uint256 bonusPercent1 = 25;
uint256 bonusPercent2 = 15;
uint256 bonusPercent3 = 0;
uint256 priceOfEMLTokenInUSDPenny = 60;
uint256 overridenBonusValue = 0;
function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) {
require( overridenValue > 0 );
require( overridenValue != priceOfEthInUSD);
priceOfEthInUSD = overridenValue;
return true;
}
function getExchangeRate() public view returns(uint256){
return priceOfEthInUSD;
}
function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) {
require( overridenValue > 0 );
require( overridenValue != overridenBonusValue);
overridenBonusValue = overridenValue;
return true;
}
/**
* @dev public function that is used to determine the current rate for token / ETH conversion
* @dev there exists a case where rate cant be set to 0, which is fine.
* @return The current token rate
*/
function getRate() public view returns(uint256) {
require( priceOfEMLTokenInUSDPenny !=0 );
require( priceOfEthInUSD !=0 );
uint256 rate;
if(overridenBonusValue > 0){
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100);
} else {
if (now <= (startTime + 1 days)) {
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100);
} if (now > (startTime + 1 days) && now <= (startTime + 2 days)) {
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent2.add(100)).div(100);
} else {
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent3.add(100)).div(100);
}
}
return rate;
}
/** @dev Initialise the Crowdsale contract.
* (can be removed for testing) _startTime Unix timestamp for the start of the token sale
* (can be removed for testing) _endTime Unix timestamp for the end of the token sale
* @param _multisigWallet Ethereum address to which the invested funds are forwarded
* @param _token Address of the token that will be rewarded for the investors
* @param _list contains a list of investors who completed KYC procedures.
*/
constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_multisigWallet != address(0));
require(_token != address(0));
require(_list != address(0));
startTime = _startTime;
endTime = _endTime;
multisigWallet = _multisigWallet;
owner = msg.sender;
token = EmalToken(_token);
list = EmalWhitelist(_list);
hardCap = token.getCrowdsaleAmount();
}
/** @dev Fallback function that can be used to buy EML tokens. Or in
* case of the owner, return ether to allow refunds in case crowdsale
* ended or paused and didnt reach soft_cap.
*/
function() external payable {
if (msg.sender == multisigWallet) {
require( (!isCrowdsaleActive()) && totalTokensSoldandAllocated<soft_cap);
} else {
if (list.isWhitelisted(msg.sender)) {
buyTokensUsingEther(msg.sender);
} else {
revert();
}
}
}
/** @dev Function for buying EML tokens using ether
* @param _investorAddr The address that should receive bought tokens
*/
function buyTokensUsingEther(address _investorAddr) internal whenNotPaused {
require(_investorAddr != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 returnToSender = 0;
// final rate after including rate value and bonus amount.
uint256 finalConversionRate = getRate();
// Calculate EML token amount to be transferred
uint256 tokens = weiAmount.mul(finalConversionRate);
// Distribute only the remaining tokens if final contribution exceeds hard cap
if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
tokens = hardCap.sub(totalTokensSoldandAllocated);
weiAmount = tokens.div(finalConversionRate);
returnToSender = msg.value.sub(weiAmount);
}
// update state and balances
etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount);
tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens);
totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens);
totalEtherRaisedByCrowdsale = totalEtherRaisedByCrowdsale.add(weiAmount);
totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);
// assert implies it should never fail
assert(token.transferFrom(owner, _investorAddr, tokens));
emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens);
// Forward funds
multisigWallet.transfer(weiAmount);
// Update token contract.
_postValidationUpdateTokenContract();
// Return funds that are over hard cap
if (returnToSender > 0) {
msg.sender.transfer(returnToSender);
}
}
function _postValidationUpdateTokenContract() internal {
/** @dev If hard cap is reachde allow token transfers after two weeks
* @dev Allow users to transfer tokens only after hardCap is reached
* @dev Notiy token contract about startTime to start transfers
*/
if (totalTokensSoldandAllocated == hardCap) {
token.setStartTimeForTokenTransfers(now + 2 weeks);
}
/** @dev If its the first token sold or allocated then set s, allow after 2 weeks
* @dev Allow users to transfer tokens only after ICO crowdsale ends.
* @dev Notify token contract about sale end time
*/
if (!isStartTimeSetForTokenTransfers) {
isStartTimeSetForTokenTransfers = true;
token.setStartTimeForTokenTransfers(endTime + 2 weeks);
}
}
/** @dev Internal function that is used to check if the incoming purchase should be accepted.
* @return True if the transaction can buy tokens
*/
function validPurchase() internal view returns(bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool minimumPurchase = msg.value >= 1*(10**18);
bool hardCapNotReached = totalTokensSoldandAllocated < hardCap;
return withinPeriod && hardCapNotReached && minimumPurchase;
}
/** @dev Public function to check if Crowdsale isActive or not
* @return True if Crowdsale event has ended
*/
function isCrowdsaleActive() public view returns(bool) {
if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){
return true;
} else {
return false;
}
}
/** @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) {
require(_owner != address(0));
return etherInvestments[_owner];
}
function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) {
require(_owner != address(0));
return tokensSoldForEther[_owner];
}
/** @dev Returns ether to token holders in case soft cap is not reached.
*/
function claimRefund() public whenNotPaused onlyOwner {
require(now>endTime);
require(totalTokensSoldandAllocated<soft_cap);
uint256 amount = etherInvestments[msg.sender];
if (address(this).balance >= amount) {
etherInvestments[msg.sender] = 0;
if (amount > 0) {
msg.sender.transfer(amount);
emit Refund(msg.sender, amount);
}
}
}
/** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC.
* functions are automatically called by ICO Sails.js app.
*/
/** @dev Allocates EML tokens to an investor address called automatically
* after receiving fiat or btc investments from KYC whitelisted investors.
* @param beneficiary The address of the investor
* @param tokenCount The number of tokens to be allocated to this address
*/
function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {
require(beneficiary != address(0));
require(validAllocation(tokenCount));
uint256 tokens = tokenCount;
/* Allocate only the remaining tokens if final contribution exceeds hard cap */
if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
tokens = hardCap.sub(totalTokensSoldandAllocated);
}
/* Update state and balances */
allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens);
totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);
totalTokensAllocated = totalTokensAllocated.add(tokens);
// assert implies it should never fail
assert(token.transferFrom(owner, beneficiary, tokens));
emit TokensAllocated(beneficiary, tokens);
/* Update token contract. */
_postValidationUpdateTokenContract();
return true;
}
function validAllocation( uint256 tokenCount ) internal view returns(bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool positiveAllocation = tokenCount > 0;
bool hardCapNotReached = totalTokensSoldandAllocated < hardCap;
return withinPeriod && positiveAllocation && hardCapNotReached;
}
/** @dev Getter function to check the amount of allocated tokens
* @param beneficiary address of the investor
*/
function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) {
require(beneficiary != address(0));
return allocatedTokens[beneficiary];
}
function getSoldandAllocatedTokens(address _addr) public view returns (uint256) {
require(_addr != address(0));
uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr));
return totalTokenCount;
}
}
pragma solidity 0.4.24;
import "./SafeMath.sol";
import "./Ownable.sol";
import "./Pausable.sol";
contract EmalToken {
// add function prototypes of only those used here
function transferFrom(address _from, address _to, uint256 _value) public returns(bool);
function getPresaleAmount() public view returns(uint256);
}
contract EmalWhitelist {
// add function prototypes of only those used here
function isWhitelisted(address investorAddr) public view returns(bool whitelisted);
}
contract EmalPresale is Ownable, Pausable {
using SafeMath for uint256;
// Start and end timestamps
uint256 public startTime;
uint256 public endTime;
// The token being sold
EmalToken public token;
// Whitelist contract used to store whitelisted addresses
EmalWhitelist public list;
// Address where funds are collected
address public multisigWallet;
// Hard cap in EMAL tokens
uint256 public hardCap;
// Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments.
uint256 public totalTokensSoldandAllocated = 0;
// Investor contributions made in ether
mapping(address => uint256) public etherInvestments;
// Tokens given to investors who sent ether investments
mapping(address => uint256) public tokensSoldForEther;
// Total ether raised by the Presale
uint256 public totalEtherRaisedByPresale = 0;
// Total number of tokens sold to investors who made payments in ether
uint256 public totalTokensSoldByEtherInvestments = 0;
// Count of allocated tokens for each investor or bounty user
mapping(address => uint256) public allocatedTokens;
// Count of total number of EML tokens that have been currently allocated to Presale investors
uint256 public totalTokensAllocated = 0;
/** @dev Event for EML token purchase using ether
* @param investorAddr Address that paid and got the tokens
* @param paidAmount The amount that was paid (in wei)
* @param tokenCount The amount of tokens that were bought
*/
event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount);
/** @dev Event fired when EML tokens are allocated to an investor account
* @param beneficiary Address that is allocated tokens
* @param tokenCount The amount of tokens that were allocated
*/
event TokensAllocated(address indexed beneficiary, uint256 tokenCount);
event TokensDeallocated(address indexed beneficiary, uint256 tokenCount);
/** @dev variables and functions which determine conversion rate from ETH to EML
* based on bonuses and current timestamp.
*/
uint256 priceOfEthInUSD = 450;
uint256 bonusPercent1 = 35;
uint256 priceOfEMLTokenInUSDPenny = 60;
uint256 overridenBonusValue = 0;
function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) {
require( overridenValue > 0 );
require( overridenValue != priceOfEthInUSD);
priceOfEthInUSD = overridenValue;
return true;
}
function getExchangeRate() public view returns(uint256){
return priceOfEthInUSD;
}
function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) {
require( overridenValue > 0 );
require( overridenValue != overridenBonusValue);
overridenBonusValue = overridenValue;
return true;
}
/** @dev public function that is used to determine the current rate for ETH to EML conversion
* @return The current token rate
*/
function getRate() public view returns(uint256) {
require(priceOfEMLTokenInUSDPenny > 0 );
require(priceOfEthInUSD > 0 );
uint256 rate;
if(overridenBonusValue > 0){
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100);
} else {
rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100);
}
return rate;
}
/** @dev Initialise the Presale contract.
* (can be removed for testing) _startTime Unix timestamp for the start of the token sale
* (can be removed for testing) _endTime Unix timestamp for the end of the token sale
* @param _multisigWallet Ethereum address to which the invested funds are forwarded
* @param _token Address of the token that will be rewarded for the investors
* @param _list contains a list of investors who completed KYC procedures.
*/
constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_multisigWallet != address(0));
require(_token != address(0));
require(_list != address(0));
startTime = _startTime;
endTime = _endTime;
multisigWallet = _multisigWallet;
owner = msg.sender;
token = EmalToken(_token);
list = EmalWhitelist(_list);
hardCap = token.getPresaleAmount();
}
/** @dev Fallback function that can be used to buy tokens.
*/
function() external payable {
if (list.isWhitelisted(msg.sender)) {
buyTokensUsingEther(msg.sender);
} else {
/* Do not accept ETH */
revert();
}
}
/** @dev Function for buying EML tokens using ether
* @param _investorAddr The address that should receive bought tokens
*/
function buyTokensUsingEther(address _investorAddr) internal whenNotPaused {
require(_investorAddr != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 returnToSender = 0;
// final rate after including rate value and bonus amount.
uint256 finalConversionRate = getRate();
// Calculate EML token amount to be transferred
uint256 tokens = weiAmount.mul(finalConversionRate);
// Distribute only the remaining tokens if final contribution exceeds hard cap
if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
tokens = hardCap.sub(totalTokensSoldandAllocated);
weiAmount = tokens.div(finalConversionRate);
returnToSender = msg.value.sub(weiAmount);
}
// update state and balances
etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount);
tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens);
totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens);
totalEtherRaisedByPresale = totalEtherRaisedByPresale.add(weiAmount);
totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);
// assert implies it should never fail
assert(token.transferFrom(owner, _investorAddr, tokens));
emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens);
// Forward funds
multisigWallet.transfer(weiAmount);
// Return funds that are over hard cap
if (returnToSender > 0) {
msg.sender.transfer(returnToSender);
}
}
/**
* @dev Internal function that is used to check if the incoming purchase should be accepted.
* @return True if the transaction can buy tokens
*/
function validPurchase() internal view returns(bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool minimumPurchase = msg.value >= 1*(10**18);
bool hardCapNotReached = totalTokensSoldandAllocated < hardCap;
return withinPeriod && hardCapNotReached && minimumPurchase;
}
/** @dev Public function to check if Presale isActive or not
* @return True if Presale event has ended
*/
function isPresaleActive() public view returns(bool) {
if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){
return true;
} else {
return false;
}
}
/** @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) {
require(_owner != address(0));
return etherInvestments[_owner];
}
function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) {
require(_owner != address(0));
return tokensSoldForEther[_owner];
}
/** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC.
* functions are automatically called by ICO Sails.js app.
*/
/** @dev Allocates EML tokens to an investor address called automatically
* after receiving fiat or btc investments from KYC whitelisted investors.
* @param beneficiary The address of the investor
* @param tokenCount The number of tokens to be allocated to this address
*/
function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {
require(beneficiary != address(0));
require(validAllocation(tokenCount));
uint256 tokens = tokenCount;
/* Allocate only the remaining tokens if final contribution exceeds hard cap */
if (totalTokensSoldandAllocated.add(tokens) > hardCap) {
tokens = hardCap.sub(totalTokensSoldandAllocated);
}
/* Update state and balances */
allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens);
totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);
totalTokensAllocated = totalTokensAllocated.add(tokens);
// assert implies it should never fail
assert(token.transferFrom(owner, beneficiary, tokens));
emit TokensAllocated(beneficiary, tokens);
return true;
}
function validAllocation( uint256 tokenCount ) internal view returns(bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool positiveAllocation = tokenCount > 0;
bool hardCapNotReached = totalTokensSoldandAllocated < hardCap;
return withinPeriod && positiveAllocation && hardCapNotReached;
}
/** @dev Getter function to check the amount of allocated tokens
* @param beneficiary address of the investor
*/
function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) {
require(beneficiary != address(0));
return allocatedTokens[beneficiary];
}
function getSoldandAllocatedTokens(address _addr) public view returns (uint256) {
require(_addr != address(0));
uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr));
return totalTokenCount;
}
}
pragma solidity 0.4.24;
import "./SafeMath.sol";
import './StandardToken.sol';
import './Ownable.sol';
contract EmalToken is StandardToken, Ownable {
using SafeMath for uint256;
string public constant symbol = "EML";
string public constant name = "e-Mal Token";
uint8 public constant decimals = 18;
// Total Number of tokens ever goint to be minted. 1 BILLION EML tokens.
uint256 private constant minting_capped_amount = 1000000000 * 10 ** uint256(decimals);
// 24% of initial supply
uint256 constant presale_amount = 120000000 * 10 ** uint256(decimals);
// 60% of inital supply
uint256 constant crowdsale_amount = 300000000 * 10 ** uint256(decimals);
// 8% of inital supply.
uint256 constant vesting_amount = 40000000 * 10 ** uint256(decimals);
// 8% of inital supply.
uint256 constant bounty_amount = 40000000 * 10 ** uint256(decimals);
uint256 private initialSupply = minting_capped_amount;
address public presaleAddress;
address public crowdsaleAddress;
address public vestingAddress;
address public bountyAddress;
/** @dev Defines the start time after which transferring of EML tokens
* will be allowed done so as to prevent early buyers from clearing out
* of their EML balance during the presale and publicsale.
*/
uint256 public startTimeForTransfers;
/** @dev to cap the total number of tokens that will ever be newly minted
* owner has to stop the minting by setting this variable to true.
*/
bool public mintingFinished = false;
/** @dev Miniting Essentials functions as per OpenZeppelin standards
*/
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/** @dev to prevent malicious use of EML tokens and to comply with Anti
* Money laundering regulations EML tokens can be frozen.
*/
mapping (address => bool) public frozenAccount;
/** @dev This generates a public event on the blockchain that will notify clients
*/
event FrozenFunds(address target, bool frozen);
event Mint(address indexed to, uint256 amount);
event MintFinished();
event Burn(address indexed burner, uint256 value);
constructor() public {
startTimeForTransfers = now - 210 days;
_totalSupply = initialSupply;
owner = msg.sender;
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, balances[owner]);
}
/* Do not accept ETH */
function() public payable {
revert();
}
/** @dev Basic setters and getters to allocate tokens for vesting factory, presale
* crowdsale and bounty this is done so that no need of actually transferring EML
* tokens to sale contracts and hence preventing EML tokens from the risk of being
* locked out in future inside the subcontracts.
*/
function setPresaleAddress(address _presaleAddress) external onlyOwner {
presaleAddress = _presaleAddress;
assert(approve(presaleAddress, presale_amount));
}
function setCrowdsaleAddress(address _crowdsaleAddress) external onlyOwner {
crowdsaleAddress = _crowdsaleAddress;
assert(approve(crowdsaleAddress, crowdsale_amount));
}
function setVestingAddress(address _vestingAddress) external onlyOwner {
vestingAddress = _vestingAddress;
assert(approve(vestingAddress, vesting_amount));
}
function setBountyAddress(address _bountyAddress) external onlyOwner {
bountyAddress = _bountyAddress;
assert(approve(bountyAddress, bounty_amount));
}
function getPresaleAmount() internal pure returns(uint256) {
return presale_amount;
}
function getCrowdsaleAmount() internal pure returns(uint256) {
return crowdsale_amount;
}
function getVestingAmount() internal pure returns(uint256) {
return vesting_amount;
}
function getBountyAmount() internal pure returns(uint256) {
return bounty_amount;
}
/** @dev Sets the start time after which transferring of EML tokens
* will be allowed done so as to prevent early buyers from clearing out
* of their EML balance during the presale and publicsale.
*/
function setStartTimeForTokenTransfers(uint256 _startTimeForTransfers) external {
require(msg.sender == crowdsaleAddress);
if (_startTimeForTransfers < startTimeForTransfers) {
startTimeForTransfers = _startTimeForTransfers;
}
}
/** @dev Transfer possible only after ICO ends and Frozen accounts
* wont be able to transfer funds to other any other account and viz.
* @notice added safeTransfer functionality
*/
function transfer(address _to, uint256 _value) public returns(bool) {
require(now >= startTimeForTransfers);
require(!frozenAccount[msg.sender]);
require(!frozenAccount[_to]);
require(super.transfer(_to, _value));
return true;
}
/** @dev Only owner's tokens can be transferred before Crowdsale ends.
* beacuse the inital supply of EML is allocated to owners acc and later
* distributed to various subcontracts.
* @notice added safeTransferFrom functionality
*/
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if (now < startTimeForTransfers) {
require(_from == owner);
}
require(super.transferFrom(_from, _to, _value));
return true;
}
/** @notice added safeApprove functionality
*/
function approve(address spender, uint256 tokens) public returns (bool){
require(super.approve(spender, tokens));
return true;
}
/** @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
* @param target Address to be frozen
* @param freeze either to freeze it or not
*/
function freezeAccount(address target, bool freeze) public onlyOwner {
require(frozenAccount[target] != freeze);
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
/** @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) public hasMintPermission canMint returns (bool) {
require(_totalSupply.add(_amount) <= minting_capped_amount);
_totalSupply = _totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/** @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
/** @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
_totalSupply = _totalSupply.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
pragma solidity 0.4.24;
import "./EmalToken.sol";
import "./SafeMath.sol";
import "./Ownable.sol";
/** @title StandardTokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner.
*/
contract StandardTokenVesting is Ownable {
using SafeMath for uint256;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/** @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
owner = msg.sender;
cliff = _start.add(_cliff);
start = _start;
}
/** @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(EmalToken token) public returns (bool){
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.transfer(beneficiary, unreleased);
emit Released(unreleased);
return true;
}
/** @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(EmalToken token) public onlyOwner returns(bool) {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.transfer(owner, refund);
emit Revoked();
return true;
}
/** @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(EmalToken token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/** @dev Calculates the amount that has already vested.
* @param token Emal token which is being vested
*/
function vestedAmount(EmalToken token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
pragma solidity 0.4.24;
import './Ownable.sol';
/** @notice This contract provides support for whitelisting addresses.
* only whitelisted addresses are allowed to send ether and buy tokens
* during preSale and Pulic crowdsale.
* @dev after deploying contract, deploy Presale / Crowdsale contract using
* EmalWhitelist address. To allow claim refund functionality and allow wallet
* owner efatoora to send ether to Crowdsale contract for refunds add wallet
* address to whitelist.
*/
contract EmalWhitelist is Ownable {
mapping(address => bool) whitelist;
event AddToWhitelist(address investorAddr);
event RemoveFromWhitelist(address investorAddr);
/** @dev Throws if operator is not whitelisted.
*/
modifier onlyIfWhitelisted(address investorAddr) {
require(whitelist[investorAddr]);
_;
}
constructor() public {
owner = msg.sender;
}
/** @dev Returns if an address is whitelisted or not
*/
function isWhitelisted(address investorAddr) public view returns(bool whitelisted) {
return whitelist[investorAddr];
}
/**
* @dev Adds an investor to whitelist
* @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements.
*/
function addToWhitelist(address investorAddr) public onlyOwner returns(bool success) {
require(investorAddr!= address(0));
whitelist[investorAddr] = true;
return true;
}
/**
* @dev Removes an investor's address from whitelist
* @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements.
*/
function removeFromWhitelist(address investorAddr) public onlyOwner returns(bool success) {
require(investorAddr!= address(0));
whitelist[investorAddr] = false;
return true;
}
}
pragma solidity 0.4.24;
contract ERC20Token {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint256 tokens) public returns (bool success);
function approve(address spender, uint256 tokens) public returns (bool success);
function transferFrom(address from, address to, uint256 tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
pragma solidity 0.4.24;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
pragma solidity 0.4.24;
import "./Ownable.sol";
/* Pausable contract */
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/** @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/** @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/** @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/** @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
pragma solidity 0.4.24;
/**
* @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;
}
}
pragma solidity 0.4.24;
import './ERC20Token.sol';
import './SafeMath.sol';
contract StandardToken is ERC20Token {
using SafeMath for uint256;
// Global variable to store total number of tokens passed from EmalToken.sol
uint256 _totalSupply;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address tokenOwner) public view returns (uint256){
return balances[tokenOwner];
}
function transfer(address to, uint256 tokens) public returns (bool){
require(to != address(0));
require(tokens > 0 && tokens <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// Transfer tokens from one address to another
function transferFrom(address from, address to, uint256 tokens) public returns (bool success){
require(to != address(0));
require(tokens > 0 && tokens <= balances[from]);
require(tokens <= allowed[from][msg.sender]);
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
emit Transfer(from, to, tokens);
return true;
}
// Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
function approve(address spender, uint256 tokens) public returns (bool success){
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// Function to check the amount of tokens that an owner allowed to a spender.
function allowance(address tokenOwner, address spender) public view returns (uint256 remaining){
return allowed[tokenOwner][spender];
}
// Increase the amount of tokens that an owner allowed to a spender.
// approve should be called when allowed[spender] == 0.
// To increment allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined)
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;
}
// Decrease the amount of tokens that an owner allowed to a spender.
// approve should be called when allowed[spender] == 0.
// To decrement allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined)
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;
}
}
pragma solidity 0.4.24;
import "./EmalToken.sol";
import "./SafeMath.sol";
import "./Ownable.sol";
/** @title StandardTokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner.
*/
contract StandardTokenVesting is Ownable {
using SafeMath for uint256;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/** @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
owner = msg.sender;
cliff = _start.add(_cliff);
start = _start;
}
/** @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(EmalToken token) public returns (bool){
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.transfer(beneficiary, unreleased);
emit Released(unreleased);
return true;
}
/** @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(EmalToken token) public onlyOwner returns(bool) {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.transfer(owner, refund);
emit Revoked();
return true;
}
/** @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(EmalToken token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/** @dev Calculates the amount that has already vested.
* @param token Emal token which is being vested
*/
function vestedAmount(EmalToken token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
| Total Number of tokens ever goint to be minted. 1 BILLION EML tokens. 24% of initial supply 60% of inital supply 8% of inital supply. 8% of inital supply. | contract EmalToken is StandardToken, Ownable {
using SafeMath for uint256;
string public constant symbol = "EML";
string public constant name = "e-Mal Token";
uint8 public constant decimals = 18;
uint256 private constant minting_capped_amount = 1000000000 * 10 ** uint256(decimals);
uint256 constant presale_amount = 120000000 * 10 ** uint256(decimals);
uint256 constant crowdsale_amount = 300000000 * 10 ** uint256(decimals);
uint256 constant vesting_amount = 40000000 * 10 ** uint256(decimals);
uint256 constant bounty_amount = 40000000 * 10 ** uint256(decimals);
uint256 private initialSupply = minting_capped_amount;
address public presaleAddress;
address public crowdsaleAddress;
address public vestingAddress;
address public bountyAddress;
uint256 public startTimeForTransfers;
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
event Mint(address indexed to, uint256 amount);
event MintFinished();
event Burn(address indexed burner, uint256 value);
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
constructor() public {
startTimeForTransfers = now - 210 days;
_totalSupply = initialSupply;
owner = msg.sender;
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, balances[owner]);
}
function() public payable {
revert();
}
function setPresaleAddress(address _presaleAddress) external onlyOwner {
presaleAddress = _presaleAddress;
assert(approve(presaleAddress, presale_amount));
}
function setCrowdsaleAddress(address _crowdsaleAddress) external onlyOwner {
crowdsaleAddress = _crowdsaleAddress;
assert(approve(crowdsaleAddress, crowdsale_amount));
}
function setVestingAddress(address _vestingAddress) external onlyOwner {
vestingAddress = _vestingAddress;
assert(approve(vestingAddress, vesting_amount));
}
function setBountyAddress(address _bountyAddress) external onlyOwner {
bountyAddress = _bountyAddress;
assert(approve(bountyAddress, bounty_amount));
}
function getPresaleAmount() internal pure returns(uint256) {
return presale_amount;
}
function getCrowdsaleAmount() internal pure returns(uint256) {
return crowdsale_amount;
}
function getVestingAmount() internal pure returns(uint256) {
return vesting_amount;
}
function getBountyAmount() internal pure returns(uint256) {
return bounty_amount;
}
function setStartTimeForTokenTransfers(uint256 _startTimeForTransfers) external {
require(msg.sender == crowdsaleAddress);
if (_startTimeForTransfers < startTimeForTransfers) {
startTimeForTransfers = _startTimeForTransfers;
}
}
function setStartTimeForTokenTransfers(uint256 _startTimeForTransfers) external {
require(msg.sender == crowdsaleAddress);
if (_startTimeForTransfers < startTimeForTransfers) {
startTimeForTransfers = _startTimeForTransfers;
}
}
function transfer(address _to, uint256 _value) public returns(bool) {
require(now >= startTimeForTransfers);
require(!frozenAccount[msg.sender]);
require(!frozenAccount[_to]);
require(super.transfer(_to, _value));
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if (now < startTimeForTransfers) {
require(_from == owner);
}
require(super.transferFrom(_from, _to, _value));
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if (now < startTimeForTransfers) {
require(_from == owner);
}
require(super.transferFrom(_from, _to, _value));
return true;
}
function approve(address spender, uint256 tokens) public returns (bool){
require(super.approve(spender, tokens));
return true;
}
function freezeAccount(address target, bool freeze) public onlyOwner {
require(frozenAccount[target] != freeze);
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
function mint(address _to, uint256 _amount) public hasMintPermission canMint returns (bool) {
require(_totalSupply.add(_amount) <= minting_capped_amount);
_totalSupply = _totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
_totalSupply = _totalSupply.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
| 7,279,318 | [
1,
5269,
3588,
434,
2430,
14103,
314,
763,
358,
506,
312,
474,
329,
18,
404,
605,
15125,
1146,
512,
1495,
2430,
18,
4248,
9,
434,
2172,
14467,
4752,
9,
434,
1208,
287,
14467,
1725,
9,
434,
1208,
287,
14467,
18,
1725,
9,
434,
1208,
287,
14467,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
7377,
287,
1345,
353,
8263,
1345,
16,
14223,
6914,
288,
203,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
533,
1071,
5381,
3273,
273,
315,
41,
1495,
14432,
203,
565,
533,
1071,
5381,
508,
273,
315,
73,
17,
49,
287,
3155,
14432,
203,
565,
2254,
28,
1071,
5381,
15105,
273,
6549,
31,
203,
203,
565,
2254,
5034,
3238,
5381,
312,
474,
310,
67,
5909,
1845,
67,
8949,
273,
15088,
3784,
380,
1728,
2826,
2254,
5034,
12,
31734,
1769,
203,
203,
565,
2254,
5034,
5381,
4075,
5349,
67,
8949,
273,
2593,
17877,
380,
1728,
2826,
2254,
5034,
12,
31734,
1769,
203,
565,
2254,
5034,
5381,
276,
492,
2377,
5349,
67,
8949,
273,
890,
12648,
380,
1728,
2826,
2254,
5034,
12,
31734,
1769,
203,
565,
2254,
5034,
225,
5381,
331,
10100,
67,
8949,
273,
1059,
17877,
380,
1728,
2826,
2254,
5034,
12,
31734,
1769,
203,
565,
2254,
5034,
5381,
324,
592,
93,
67,
8949,
273,
1059,
17877,
380,
1728,
2826,
2254,
5034,
12,
31734,
1769,
203,
377,
203,
565,
2254,
5034,
3238,
2172,
3088,
1283,
273,
312,
474,
310,
67,
5909,
1845,
67,
8949,
31,
203,
203,
565,
1758,
1071,
4075,
5349,
1887,
31,
203,
565,
1758,
1071,
276,
492,
2377,
5349,
1887,
31,
203,
565,
1758,
1071,
331,
10100,
1887,
31,
203,
565,
1758,
1071,
324,
592,
93,
1887,
31,
203,
203,
203,
203,
565,
2254,
5034,
1071,
8657,
1290,
1429,
18881,
31,
203,
203,
565,
1426,
1071,
312,
474,
310,
10577,
273,
629,
31,
203,
203,
565,
9606,
848,
2
]
|
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/drafts/Counters.sol";
/**
* 数据合约
*/
contract IsLandStorage {
using Counters for Counters.Counter;
address public proxy;
// 地图类型购买信息
mapping(uint256 => Counters.Counter) public payedTotalCount;
// 地图id和土地映射
mapping(uint256 => IsLandStruct) public landNftMap;
//小型岛
uint8 constant public GENRE_SMALL = 1;
//中型岛
uint8 constant public GENRE_MEDIUM = 2;
//小型岛
uint8 constant public GENRE_LARGE = 3;
//未知岛屿
uint8 constant public GENRE_SECRET = 9;
// 地图块信息
struct IsLandStruct {
uint256 genre;
uint256 bornAt; //生成时间
address owner; //拥有者
}
constructor(address _proxy) public {
require(_proxy != address(0), "zero address is not allowed");
proxy = _proxy;
}
// 验证对model的操作是否来源于Proxy, 写成func, 节省gas消耗
function _isAuthorized() view internal {
require(msg.sender == proxy, "AccountStorage: must be proxy");
}
// 购买地图
function payLand(uint256 mapId, uint8 genre, address owner) external {
_isAuthorized();
// 校验地址是否为空
require (owner == address(0));
// 判断参数类型是否正确
require(mapId == uint256(uint32(mapId)));
require(genre == GENRE_SMALL || genre == GENRE_MEDIUM || genre == GENRE_LARGE);
// 累加总计值
payedTotalCount[genre].increment();
// 存储数据到区块上
IsLandStruct memory isLandStruct = IsLandStruct(genre, now, owner);
landNftMap[mapId] = isLandStruct;
}
// 转让地图
function transferIsLand(uint256 mapId, address to) external {
_isAuthorized();
require(to != address(0));
// 判断参数类型是否正确
require(mapId == uint256(uint32(mapId)));
// 存储数据到区块上
IsLandStruct memory isLandStruct = landNftMap[mapId];
delete landNftMap[mapId];
IsLandStruct memory newIsLandStruct = IsLandStruct(isLandStruct.genre, isLandStruct.bornAt, to);
landNftMap[mapId] = newIsLandStruct;
}
} | * 数据合约/ 地图类型购买信息 地图id和土地映射小型岛中型岛小型岛未知岛屿 地图块信息 | contract IsLandStorage {
using Counters for Counters.Counter;
address public proxy;
mapping(uint256 => Counters.Counter) public payedTotalCount;
mapping(uint256 => IsLandStruct) public landNftMap;
uint8 constant public GENRE_SMALL = 1;
uint8 constant public GENRE_MEDIUM = 2;
uint8 constant public GENRE_LARGE = 3;
uint8 constant public GENRE_SECRET = 9;
struct IsLandStruct {
uint256 genre;
}
constructor(address _proxy) public {
require(_proxy != address(0), "zero address is not allowed");
proxy = _proxy;
}
function _isAuthorized() view internal {
require(msg.sender == proxy, "AccountStorage: must be proxy");
}
function payLand(uint256 mapId, uint8 genre, address owner) external {
_isAuthorized();
require (owner == address(0));
require(mapId == uint256(uint32(mapId)));
require(genre == GENRE_SMALL || genre == GENRE_MEDIUM || genre == GENRE_LARGE);
payedTotalCount[genre].increment();
IsLandStruct memory isLandStruct = IsLandStruct(genre, now, owner);
landNftMap[mapId] = isLandStruct;
}
function transferIsLand(uint256 mapId, address to) external {
_isAuthorized();
require(to != address(0));
require(mapId == uint256(uint32(mapId)));
IsLandStruct memory isLandStruct = landNftMap[mapId];
delete landNftMap[mapId];
IsLandStruct memory newIsLandStruct = IsLandStruct(isLandStruct.genre, isLandStruct.bornAt, to);
landNftMap[mapId] = newIsLandStruct;
}
} | 5,470,622 | [
1,
167,
248,
113,
167,
240,
111,
166,
243,
235,
168,
123,
104,
19,
225,
166,
255,
113,
166,
254,
127,
168,
114,
124,
166,
257,
238,
169,
117,
260,
165,
122,
113,
165,
128,
99,
167,
228,
112,
225,
166,
255,
113,
166,
254,
127,
350,
166,
245,
239,
166,
255,
258,
166,
255,
113,
167,
251,
259,
166,
113,
231,
166,
113,
242,
166,
257,
238,
166,
115,
254,
165,
121,
260,
166,
257,
238,
166,
115,
254,
166,
113,
242,
166,
257,
238,
166,
115,
254,
167,
255,
108,
168,
258,
103,
166,
115,
254,
166,
114,
128,
225,
166,
255,
113,
166,
254,
127,
166,
256,
250,
165,
128,
99,
167,
228,
112,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
2585,
29398,
3245,
225,
288,
203,
203,
202,
9940,
9354,
87,
364,
9354,
87,
18,
4789,
31,
203,
203,
202,
2867,
1071,
2889,
31,
203,
202,
203,
565,
2874,
12,
11890,
5034,
516,
9354,
87,
18,
4789,
13,
1071,
8843,
329,
5269,
1380,
31,
203,
565,
2874,
12,
11890,
5034,
516,
2585,
29398,
3823,
13,
1071,
19193,
50,
1222,
863,
31,
203,
203,
565,
2254,
28,
5381,
1071,
611,
1157,
862,
67,
23882,
273,
404,
31,
203,
565,
2254,
28,
5381,
1071,
611,
1157,
862,
67,
15971,
2799,
273,
576,
31,
203,
565,
2254,
28,
5381,
1071,
611,
1157,
862,
67,
48,
28847,
273,
890,
31,
203,
565,
2254,
28,
5381,
1071,
611,
1157,
862,
67,
20455,
273,
2468,
31,
203,
203,
565,
1958,
2585,
29398,
3823,
288,
203,
3639,
2254,
5034,
3157,
266,
31,
203,
565,
289,
203,
202,
203,
225,
202,
12316,
12,
2867,
389,
5656,
13,
1071,
288,
203,
3639,
2583,
24899,
5656,
480,
1758,
12,
20,
3631,
315,
7124,
1758,
353,
486,
2935,
8863,
203,
3639,
2889,
273,
389,
5656,
31,
203,
565,
289,
203,
203,
225,
202,
915,
389,
291,
15341,
1435,
1476,
2713,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
2889,
16,
315,
3032,
3245,
30,
1297,
506,
2889,
8863,
203,
565,
289,
203,
203,
565,
445,
8843,
29398,
12,
11890,
5034,
852,
548,
16,
2254,
28,
3157,
266,
16,
1758,
3410,
13,
3903,
288,
203,
202,
202,
67,
291,
15341,
5621,
203,
3639,
2583,
261,
8443,
422,
1758,
12,
20,
10019,
203,
3639,
2583,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.7.0;
import './interfaces/IContribute.sol';
import './utils/MathUtils.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '@openzeppelin/contracts/math/SafeMath.sol';
import '@openzeppelin/contracts/utils/ReentrancyGuard.sol';
contract Genesis is ReentrancyGuard {
using SafeMath for uint256;
using MathUtils for uint256;
using SafeERC20 for IERC20;
event Deposit(address indexed from, uint256 amount);
event Claim(address indexed user, uint256 amount);
/// @notice End date and time of the Genesis Mint Event (GME).
uint256 public endTime;
/// @notice Total tokens acquired during the GME.
uint256 public totalTokensReceived;
/// @notice Total invested in the GME.
uint256 public totalInvested;
/// @notice mUSD reserve instance.
address public reserve;
/// @notice Minter contract instance.
address public contribute;
/// @notice Balance tracker of accounts who have deposited funds.
mapping(address => uint256) balance;
bool private _toggle;
modifier GMEOpen {
require(block.timestamp <= endTime, 'GME is over');
_;
}
modifier GMEOver {
require(block.timestamp > endTime, 'GME not over');
_;
}
constructor(
address _reserve,
address _contribute,
uint256 _endTime
) public {
reserve = _reserve;
contribute = _contribute;
endTime = _endTime;
}
/// @notice Receives mUSD from accounts participating in the GME
/// updating their internal balance.
/// @dev Value to be deposited needs to be approved first.
/// @param value The reserve amount being contributed.
function deposit(uint256 value) external GMEOpen {
require(value >= 0.01 ether, 'Minimum contribution is 0.01');
IERC20(reserve).safeTransferFrom(msg.sender, address(this), value);
balance[msg.sender] = balance[msg.sender].add(value);
totalInvested = totalInvested.add(value);
require(_invest(value), 'Investment failed');
totalTokensReceived = totalTokenBalance();
emit Deposit(msg.sender, value);
}
/// @notice Allows anyone to conclude the GME.
function concludeGME() external GMEOver {
IContribute(contribute).concludeGME();
}
/// @notice Calculates account share and sends acquired tokens
// to account after GME event is over.
function claim() external nonReentrant GMEOver {
require(balance[msg.sender] > 0, 'No tokens to claim');
uint256 share = _calculateShare(msg.sender);
balance[msg.sender] = 0;
IERC20(IContribute(contribute).token()).safeTransfer(msg.sender, share);
emit Claim(msg.sender, share);
}
/// @notice Calculates account share
/// @param account Address of the account to calculate the shares from.
/// @return Total shares of given account.
function getShare(address account) external view returns (uint256) {
return _calculateShare(account);
}
/// @notice Funds deposited per account.
/// @param account Address of the account to retrieve the balance from.
/// @return Total funds deposited.
function getBalance(address account) external view returns (uint256) {
return balance[account];
}
/// @notice Total funds deposited into the Genesis contract.
/// @return Current reserve balance of this contract.
function totalReserveBalance() external view returns (uint256) {
return IERC20(reserve).balanceOf(address(this));
}
/// @notice Total tokens minted to this contract.
/// @return Current token balance of this contract.
function totalTokenBalance() public view returns (uint256) {
return IERC20(IContribute(contribute).token()).balanceOf(address(this));
}
/// @notice Worker function which invests the deposited amount.
/// @param _amount Value to be invested.
/// @return True if successful.
function _invest(uint256 _amount) internal returns (bool) {
IERC20(reserve).safeApprove(contribute, _amount);
IContribute(contribute).genesisInvest(_amount);
return true;
}
/// @notice Calculates share of a given account.
/// @param _account Account to calculate the share from.
/// @return Shares of given account.
function _calculateShare(address _account) internal view returns (uint256) {
// userShare*tokenSupply/totalInvested
uint256 a = balance[_account].mul(totalTokensReceived);
uint256 b = totalInvested;
uint256 share = a.roundedDiv(b);
return share;
}
}
| @notice Calculates share of a given account. @param _account Account to calculate the share from. @return Shares of given account. userShare*tokenSupply/totalInvested | function _calculateShare(address _account) internal view returns (uint256) {
uint256 a = balance[_account].mul(totalTokensReceived);
uint256 b = totalInvested;
uint256 share = a.roundedDiv(b);
return share;
}
| 2,525,490 | [
1,
10587,
7433,
434,
279,
864,
2236,
18,
225,
389,
4631,
6590,
358,
4604,
326,
7433,
628,
18,
327,
2638,
4807,
434,
864,
2236,
18,
729,
9535,
2316,
3088,
1283,
19,
4963,
3605,
3149,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
389,
11162,
9535,
12,
2867,
389,
4631,
13,
2713,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
565,
2254,
5034,
279,
273,
11013,
63,
67,
4631,
8009,
16411,
12,
4963,
5157,
8872,
1769,
203,
565,
2254,
5034,
324,
273,
2078,
3605,
3149,
31,
203,
565,
2254,
5034,
7433,
273,
279,
18,
27561,
7244,
12,
70,
1769,
203,
565,
327,
7433,
31,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
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;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./RoleAware.sol";
import "./Fund.sol";
import "./CrossMarginTrading.sol";
import "../libraries/IncentiveReporter.sol";
/**
@title Here we support staking for MFI incentives as well as
staking to perform the maintenance role.
*/
contract Admin is RoleAware {
/// Margenswap (MFI) token address
address public immutable MFI;
mapping(address => uint256) public stakes;
uint256 public totalStakes;
uint256 public constant mfiStakeTranche = 1;
uint256 public maintenanceStakePerBlock = 15 ether;
mapping(address => address) public nextMaintenanceStaker;
mapping(address => mapping(address => bool)) public maintenanceDelegateTo;
address public currentMaintenanceStaker;
address public prevMaintenanceStaker;
uint256 public currentMaintenanceStakerStartBlock;
address public immutable lockedMFI;
constructor(
address _MFI,
address _lockedMFI,
address lockedMFIDelegate,
address _roles
) RoleAware(_roles) {
MFI = _MFI;
lockedMFI = _lockedMFI;
// for initialization purposes and to ensure availability of service
// the team's locked MFI participate in maintenance staking only
// (not in the incentive staking part)
// this implies some trust of the team to execute, which we deem reasonable
// since the locked stake is temporary and diminishing as well as the fact
// that the team is heavily invested in the protocol and incentivized
// by fees like any other maintainer
// furthermore others could step in to liquidate via the attacker route
// and take away the team fees if they were delinquent
nextMaintenanceStaker[_lockedMFI] = _lockedMFI;
currentMaintenanceStaker = _lockedMFI;
prevMaintenanceStaker = _lockedMFI;
maintenanceDelegateTo[_lockedMFI][lockedMFIDelegate];
currentMaintenanceStakerStartBlock = block.number;
}
/// Maintence stake setter
function setMaintenanceStakePerBlock(uint256 amount)
external
onlyOwnerExec
{
maintenanceStakePerBlock = amount;
}
function _stake(address holder, uint256 amount) internal {
Fund(fund()).depositFor(holder, MFI, amount);
stakes[holder] += amount;
totalStakes += amount;
IncentiveReporter.addToClaimAmount(MFI, holder, amount);
}
/// Deposit a stake for sender
function depositStake(uint256 amount) external {
_stake(msg.sender, amount);
}
function _withdrawStake(
address holder,
uint256 amount,
address recipient
) internal {
// overflow failure desirable
stakes[holder] -= amount;
totalStakes -= amount;
Fund(fund()).withdraw(MFI, recipient, amount);
IncentiveReporter.subtractFromClaimAmount(MFI, holder, amount);
}
/// Withdraw stake for sender
function withdrawStake(uint256 amount) external {
require(
!isAuthorizedStaker(msg.sender),
"You can't withdraw while you're authorized staker"
);
_withdrawStake(msg.sender, amount, msg.sender);
}
/// Deposit maintenance stake
function depositMaintenanceStake(uint256 amount) external {
require(
amount + stakes[msg.sender] >= maintenanceStakePerBlock,
"Insufficient stake to call even one block"
);
_stake(msg.sender, amount);
if (nextMaintenanceStaker[msg.sender] == address(0)) {
nextMaintenanceStaker[msg.sender] = getUpdatedCurrentStaker();
nextMaintenanceStaker[prevMaintenanceStaker] = msg.sender;
}
}
function getMaintenanceStakerStake(address staker)
public
view
returns (uint256)
{
if (staker == lockedMFI) {
return IERC20(MFI).balanceOf(lockedMFI) / 2;
} else {
return stakes[staker];
}
}
function getUpdatedCurrentStaker() public returns (address) {
uint256 currentStake =
getMaintenanceStakerStake(currentMaintenanceStaker);
if (
(block.number - currentMaintenanceStakerStartBlock) *
maintenanceStakePerBlock >=
currentStake
) {
currentMaintenanceStakerStartBlock = block.number;
prevMaintenanceStaker = currentMaintenanceStaker;
currentMaintenanceStaker = nextMaintenanceStaker[
currentMaintenanceStaker
];
currentStake = getMaintenanceStakerStake(currentMaintenanceStaker);
if (maintenanceStakePerBlock > currentStake) {
// delete current from daisy chain
address nextOne =
nextMaintenanceStaker[currentMaintenanceStaker];
nextMaintenanceStaker[prevMaintenanceStaker] = nextOne;
nextMaintenanceStaker[currentMaintenanceStaker] = address(0);
currentMaintenanceStaker = nextOne;
currentStake = getMaintenanceStakerStake(
currentMaintenanceStaker
);
}
}
return currentMaintenanceStaker;
}
function viewCurrentMaintenanceStaker()
public
view
returns (address staker, uint256 startBlock)
{
staker = currentMaintenanceStaker;
uint256 currentStake = getMaintenanceStakerStake(staker);
startBlock = currentMaintenanceStakerStartBlock;
if (
(block.number - startBlock) * maintenanceStakePerBlock >=
currentStake
) {
staker = nextMaintenanceStaker[staker];
currentStake = getMaintenanceStakerStake(staker);
startBlock = block.number;
if (maintenanceStakePerBlock > currentStake) {
staker = nextMaintenanceStaker[staker];
}
}
}
/// Add a delegate for staker
function addDelegate(address forStaker, address delegate) external {
require(
msg.sender == forStaker ||
maintenanceDelegateTo[forStaker][msg.sender],
"msg.sender not authorized to delegate for staker"
);
maintenanceDelegateTo[forStaker][delegate] = true;
}
/// Remove a delegate for staker
function removeDelegate(address forStaker, address delegate) external {
require(
msg.sender == forStaker ||
maintenanceDelegateTo[forStaker][msg.sender],
"msg.sender not authorized to delegate for staker"
);
maintenanceDelegateTo[forStaker][delegate] = false;
}
function isAuthorizedStaker(address caller)
public
returns (bool isAuthorized)
{
address currentStaker = getUpdatedCurrentStaker();
isAuthorized =
currentStaker == caller ||
maintenanceDelegateTo[currentStaker][caller];
}
/// Penalize a staker
function penalizeMaintenanceStake(
address maintainer,
uint256 penalty,
address recipient
) external returns (uint256 stakeTaken) {
require(
isStakePenalizer(msg.sender),
"msg.sender not authorized to penalize stakers"
);
if (penalty > stakes[maintainer]) {
stakeTaken = stakes[maintainer];
} else {
stakeTaken = penalty;
}
_withdrawStake(maintainer, stakeTaken, recipient);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "./RoleAware.sol";
/// @title Base lending behavior
abstract contract BaseLending {
uint256 constant FP48 = 2**48;
uint256 constant ACCUMULATOR_INIT = 10**18;
uint256 constant hoursPerYear = 365 days / (1 hours);
uint256 constant CHANGE_POINT = 79;
uint256 public normalRatePerPercent =
(FP48 * 15) / hoursPerYear / CHANGE_POINT / 100;
uint256 public highRatePerPercent =
(FP48 * (194 - 15)) / hoursPerYear / (100 - CHANGE_POINT) / 100;
struct YieldAccumulator {
uint256 accumulatorFP;
uint256 lastUpdated;
uint256 hourlyYieldFP;
}
struct LendingMetadata {
uint256 totalLending;
uint256 totalBorrowed;
uint256 lendingCap;
}
mapping(address => LendingMetadata) public lendingMeta;
/// @dev accumulate interest per issuer (like compound indices)
mapping(address => YieldAccumulator) public borrowYieldAccumulators;
/// @dev simple formula for calculating interest relative to accumulator
function applyInterest(
uint256 balance,
uint256 accumulatorFP,
uint256 yieldQuotientFP
) internal pure returns (uint256) {
// 1 * FP / FP = 1
return (balance * accumulatorFP) / yieldQuotientFP;
}
function currentLendingRateFP(uint256 totalLending, uint256 totalBorrowing)
internal
view
returns (uint256 rate)
{
rate = FP48;
uint256 utilizationPercent = (100 * totalBorrowing) / totalLending;
if (utilizationPercent < CHANGE_POINT) {
rate += utilizationPercent * normalRatePerPercent;
} else {
rate +=
CHANGE_POINT *
normalRatePerPercent +
(utilizationPercent - CHANGE_POINT) *
highRatePerPercent;
}
}
/// @dev minimum
function min(uint256 a, uint256 b) internal pure returns (uint256) {
if (a > b) {
return b;
} else {
return a;
}
}
/// @dev maximum
function max(uint256 a, uint256 b) internal pure returns (uint256) {
if (a > b) {
return a;
} else {
return b;
}
}
/// Available tokens to this issuance
function issuanceBalance(address issuance)
internal
view
virtual
returns (uint256);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "./Fund.sol";
import "../libraries/UniswapStyleLib.sol";
abstract contract BaseRouter {
modifier ensure(uint256 deadline) {
require(deadline >= block.timestamp, "Trade has expired");
_;
}
// **** SWAP ****
/// @dev requires the initial amount to have already been sent to the first pair
/// and for pairs to be vetted (which getAmountsIn / getAmountsOut do)
function _swap(
uint256[] memory amounts,
address[] memory pairs,
address[] memory tokens,
address _to
) internal {
for (uint256 i; i < pairs.length; i++) {
(address input, address output) = (tokens[i], tokens[i + 1]);
(address token0, ) = UniswapStyleLib.sortTokens(input, output);
uint256 amountOut = amounts[i + 1];
(uint256 amount0Out, uint256 amount1Out) =
input == token0
? (uint256(0), amountOut)
: (amountOut, uint256(0));
address to = i < pairs.length - 1 ? pairs[i + 1] : _to;
IUniswapV2Pair pair = IUniswapV2Pair(pairs[i]);
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./Fund.sol";
import "./Lending.sol";
import "./RoleAware.sol";
import "./PriceAware.sol";
// Goal: all external functions only accessible to margintrader role
// except for view functions of course
struct CrossMarginAccount {
uint256 lastDepositBlock;
address[] borrowTokens;
// borrowed token address => amount
mapping(address => uint256) borrowed;
// borrowed token => yield quotient
mapping(address => uint256) borrowedYieldQuotientsFP;
address[] holdingTokens;
// token held in portfolio => amount
mapping(address => uint256) holdings;
// boolean value of whether an account holds a token
mapping(address => bool) holdsToken;
}
abstract contract CrossMarginAccounts is RoleAware, PriceAware {
/// @dev gets used in calculating how much accounts can borrow
uint256 public leveragePercent = 300;
/// @dev percentage of assets held per assets borrowed at which to liquidate
uint256 public liquidationThresholdPercent = 115;
/// @dev record of all cross margin accounts
mapping(address => CrossMarginAccount) internal marginAccounts;
/// @dev total token caps
mapping(address => uint256) public tokenCaps;
/// @dev tracks total of short positions per token
mapping(address => uint256) public totalShort;
/// @dev tracks total of long positions per token
mapping(address => uint256) public totalLong;
uint256 public coolingOffPeriod = 10;
/// @dev add an asset to be held by account
function addHolding(
CrossMarginAccount storage account,
address token,
uint256 depositAmount
) internal {
if (!hasHoldingToken(account, token)) {
account.holdingTokens.push(token);
account.holdsToken[token] = true;
}
account.holdings[token] += depositAmount;
}
/// @dev adjust account to reflect borrowing of token amount
function borrow(
CrossMarginAccount storage account,
address borrowToken,
uint256 borrowAmount
) internal {
if (!hasBorrowedToken(account, borrowToken)) {
account.borrowTokens.push(borrowToken);
account.borrowedYieldQuotientsFP[borrowToken] = Lending(lending())
.getUpdatedBorrowYieldAccuFP(borrowToken);
account.borrowed[borrowToken] = borrowAmount;
} else {
(uint256 oldBorrowed, uint256 accumulatorFP) =
Lending(lending()).applyBorrowInterest(
account.borrowed[borrowToken],
borrowToken,
account.borrowedYieldQuotientsFP[borrowToken]
);
account.borrowedYieldQuotientsFP[borrowToken] = accumulatorFP;
account.borrowed[borrowToken] = oldBorrowed + borrowAmount;
}
require(positiveBalance(account), "Insufficient balance");
}
/// @dev checks whether account is in the black, deposit + earnings relative to borrowed
function positiveBalance(CrossMarginAccount storage account)
internal
returns (bool)
{
uint256 loan = loanInPeg(account);
uint256 holdings = holdingsInPeg(account);
// The following condition should hold:
// holdings / loan >= leveragePercent / (leveragePercent - 100)
// =>
return holdings * (leveragePercent - 100) >= loan * leveragePercent;
}
/// @dev internal function adjusting holding and borrow balances when debt extinguished
function extinguishDebt(
CrossMarginAccount storage account,
address debtToken,
uint256 extinguishAmount
) internal {
// will throw if insufficient funds
(uint256 borrowAmount, uint256 newYieldQuot) =
Lending(lending()).applyBorrowInterest(
account.borrowed[debtToken],
debtToken,
account.borrowedYieldQuotientsFP[debtToken]
);
uint256 newBorrowAmount = borrowAmount - extinguishAmount;
account.borrowed[debtToken] = newBorrowAmount;
if (newBorrowAmount > 0) {
account.borrowedYieldQuotientsFP[debtToken] = newYieldQuot;
} else {
delete account.borrowedYieldQuotientsFP[debtToken];
bool decrement = false;
uint256 len = account.borrowTokens.length;
for (uint256 i; len > i; i++) {
address currToken = account.borrowTokens[i];
if (currToken == debtToken) {
decrement = true;
} else if (decrement) {
account.borrowTokens[i - 1] = currToken;
}
}
account.borrowTokens.pop();
}
}
/// @dev checks whether an account holds a token
function hasHoldingToken(CrossMarginAccount storage account, address token)
internal
view
returns (bool)
{
return account.holdsToken[token];
}
/// @dev checks whether an account has borrowed a token
function hasBorrowedToken(CrossMarginAccount storage account, address token)
internal
view
returns (bool)
{
return account.borrowedYieldQuotientsFP[token] > 0;
}
/// @dev calculate total loan in reference currency, including compound interest
function loanInPeg(CrossMarginAccount storage account)
internal
returns (uint256)
{
return
sumTokensInPegWithYield(
account.borrowTokens,
account.borrowed,
account.borrowedYieldQuotientsFP
);
}
/// @dev total of assets of account, expressed in reference currency
function holdingsInPeg(CrossMarginAccount storage account)
internal
returns (uint256)
{
return sumTokensInPeg(account.holdingTokens, account.holdings);
}
/// @dev check whether an account can/should be liquidated
function belowMaintenanceThreshold(CrossMarginAccount storage account)
internal
returns (bool)
{
uint256 loan = loanInPeg(account);
uint256 holdings = holdingsInPeg(account);
// The following should hold:
// holdings / loan >= 1.1
// => holdings >= loan * 1.1
return 100 * holdings < liquidationThresholdPercent * loan;
}
/// @dev go through list of tokens and their amounts, summing up
function sumTokensInPeg(
address[] storage tokens,
mapping(address => uint256) storage amounts
) internal returns (uint256 totalPeg) {
uint256 len = tokens.length;
for (uint256 tokenId; tokenId < len; tokenId++) {
address token = tokens[tokenId];
totalPeg += PriceAware.getCurrentPriceInPeg(token, amounts[token]);
}
}
/// @dev go through list of tokens and their amounts, summing up
function viewTokensInPeg(
address[] storage tokens,
mapping(address => uint256) storage amounts
) internal view returns (uint256 totalPeg) {
uint256 len = tokens.length;
for (uint256 tokenId; tokenId < len; tokenId++) {
address token = tokens[tokenId];
totalPeg += PriceAware.viewCurrentPriceInPeg(token, amounts[token]);
}
}
/// @dev go through list of tokens and ammounts, summing up with interest
function sumTokensInPegWithYield(
address[] storage tokens,
mapping(address => uint256) storage amounts,
mapping(address => uint256) storage yieldQuotientsFP
) internal returns (uint256 totalPeg) {
uint256 len = tokens.length;
for (uint256 tokenId; tokenId < len; tokenId++) {
address token = tokens[tokenId];
totalPeg += yieldTokenInPeg(
token,
amounts[token],
yieldQuotientsFP
);
}
}
/// @dev go through list of tokens and ammounts, summing up with interest
function viewTokensInPegWithYield(
address[] storage tokens,
mapping(address => uint256) storage amounts,
mapping(address => uint256) storage yieldQuotientsFP
) internal view returns (uint256 totalPeg) {
uint256 len = tokens.length;
for (uint256 tokenId; tokenId < len; tokenId++) {
address token = tokens[tokenId];
totalPeg += viewYieldTokenInPeg(
token,
amounts[token],
yieldQuotientsFP
);
}
}
/// @dev calculate yield for token amount and convert to reference currency
function yieldTokenInPeg(
address token,
uint256 amount,
mapping(address => uint256) storage yieldQuotientsFP
) internal returns (uint256) {
uint256 yieldFP =
Lending(lending()).viewAccumulatedBorrowingYieldFP(token);
// 1 * FP / FP = 1
uint256 amountInToken = (amount * yieldFP) / yieldQuotientsFP[token];
return PriceAware.getCurrentPriceInPeg(token, amountInToken);
}
/// @dev calculate yield for token amount and convert to reference currency
function viewYieldTokenInPeg(
address token,
uint256 amount,
mapping(address => uint256) storage yieldQuotientsFP
) internal view returns (uint256) {
uint256 yieldFP =
Lending(lending()).viewAccumulatedBorrowingYieldFP(token);
// 1 * FP / FP = 1
uint256 amountInToken = (amount * yieldFP) / yieldQuotientsFP[token];
return PriceAware.viewCurrentPriceInPeg(token, amountInToken);
}
/// @dev move tokens from one holding to another
function adjustAmounts(
CrossMarginAccount storage account,
address fromToken,
address toToken,
uint256 soldAmount,
uint256 boughtAmount
) internal {
account.holdings[fromToken] = account.holdings[fromToken] - soldAmount;
addHolding(account, toToken, boughtAmount);
}
/// sets borrow and holding to zero
function deleteAccount(CrossMarginAccount storage account) internal {
uint256 len = account.borrowTokens.length;
for (uint256 borrowIdx; len > borrowIdx; borrowIdx++) {
address borrowToken = account.borrowTokens[borrowIdx];
totalShort[borrowToken] -= account.borrowed[borrowToken];
account.borrowed[borrowToken] = 0;
account.borrowedYieldQuotientsFP[borrowToken] = 0;
}
len = account.holdingTokens.length;
for (uint256 holdingIdx; len > holdingIdx; holdingIdx++) {
address holdingToken = account.holdingTokens[holdingIdx];
totalLong[holdingToken] -= account.holdings[holdingToken];
account.holdings[holdingToken] = 0;
account.holdsToken[holdingToken] = false;
}
delete account.borrowTokens;
delete account.holdingTokens;
}
/// @dev minimum
function min(uint256 a, uint256 b) internal pure returns (uint256) {
if (a > b) {
return b;
} else {
return a;
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "./CrossMarginAccounts.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
@title Handles liquidation of accounts below maintenance threshold
@notice Liquidation can be called by the authorized staker,
as determined in the Admin contract.
If the authorized staker is delinquent, other participants can jump
in and attack, taking their fees and potentially even their stake,
depending how delinquent the responsible authorized staker is.
*/
abstract contract CrossMarginLiquidation is CrossMarginAccounts {
event LiquidationShortfall(uint256 amount);
event AccountLiquidated(address account);
struct Liquidation {
uint256 buy;
uint256 sell;
uint256 blockNum;
}
/// record kept around until a stake attacker can claim their reward
struct AccountLiqRecord {
uint256 blockNum;
address loser;
uint256 amount;
address stakeAttacker;
}
mapping(address => Liquidation) liquidationAmounts;
address[] internal liquidationTokens;
address[] internal tradersToLiquidate;
mapping(address => uint256) public maintenanceFailures;
mapping(address => AccountLiqRecord) public stakeAttackRecords;
uint256 public avgLiquidationPerCall = 10;
uint256 public liqStakeAttackWindow = 5;
uint256 public MAINTAINER_CUT_PERCENT = 5;
uint256 public failureThreshold = 10;
/// Set failure threshold
function setFailureThreshold(uint256 threshFactor) external onlyOwnerExec {
failureThreshold = threshFactor;
}
/// Set liquidity stake attack window
function setLiqStakeAttackWindow(uint256 window) external onlyOwnerExec {
liqStakeAttackWindow = window;
}
/// Set maintainer's percent cut
function setMaintainerCutPercent(uint256 cut) external onlyOwnerExec {
MAINTAINER_CUT_PERCENT = cut;
}
/// @dev calcLiquidationAmounts does a number of tasks in this contract
/// and some of them are not straightforward.
/// First of all it aggregates liquidation amounts,
/// as well as which traders are ripe for liquidation, in storage (not in memory)
/// owing to the fact that arrays can't be pushed to and hash maps don't
/// exist in memory.
/// Then it also returns any stake attack funds if the stake was unsuccessful
/// (i.e. current caller is authorized). Also see context below.
function calcLiquidationAmounts(
address[] memory liquidationCandidates,
bool isAuthorized
) internal returns (uint256 attackReturns) {
liquidationTokens = new address[](0);
tradersToLiquidate = new address[](0);
for (
uint256 traderIndex = 0;
liquidationCandidates.length > traderIndex;
traderIndex++
) {
address traderAddress = liquidationCandidates[traderIndex];
CrossMarginAccount storage account = marginAccounts[traderAddress];
if (belowMaintenanceThreshold(account)) {
tradersToLiquidate.push(traderAddress);
uint256 len = account.holdingTokens.length;
for (uint256 sellIdx = 0; len > sellIdx; sellIdx++) {
address token = account.holdingTokens[sellIdx];
Liquidation storage liquidation = liquidationAmounts[token];
if (liquidation.blockNum != block.number) {
liquidation.sell = account.holdings[token];
liquidation.buy = 0;
liquidation.blockNum = block.number;
liquidationTokens.push(token);
} else {
liquidation.sell += account.holdings[token];
}
}
len = account.borrowTokens.length;
for (uint256 buyIdx = 0; len > buyIdx; buyIdx++) {
address token = account.borrowTokens[buyIdx];
Liquidation storage liquidation = liquidationAmounts[token];
(uint256 loanAmount, ) =
Lending(lending()).applyBorrowInterest(
account.borrowed[token],
token,
account.borrowedYieldQuotientsFP[token]
);
Lending(lending()).payOff(token, loanAmount);
if (liquidation.blockNum != block.number) {
liquidation.sell = 0;
liquidation.buy = loanAmount;
liquidation.blockNum = block.number;
liquidationTokens.push(token);
} else {
liquidation.buy += loanAmount;
}
}
}
AccountLiqRecord storage liqAttackRecord =
stakeAttackRecords[traderAddress];
if (isAuthorized) {
attackReturns += _disburseLiqAttack(liqAttackRecord);
}
}
}
function _disburseLiqAttack(AccountLiqRecord storage liqAttackRecord)
internal
returns (uint256 returnAmount)
{
if (liqAttackRecord.amount > 0) {
// validate attack records, if any
uint256 blockDiff =
min(
block.number - liqAttackRecord.blockNum,
liqStakeAttackWindow
);
uint256 attackerCut =
(liqAttackRecord.amount * blockDiff) / liqStakeAttackWindow;
Fund(fund()).withdraw(
PriceAware.peg,
liqAttackRecord.stakeAttacker,
attackerCut
);
Admin a = Admin(admin());
uint256 penalty =
(a.maintenanceStakePerBlock() * attackerCut) /
avgLiquidationPerCall;
a.penalizeMaintenanceStake(
liqAttackRecord.loser,
penalty,
liqAttackRecord.stakeAttacker
);
// return remainder, after cut was taken to authorized stakekr
returnAmount = liqAttackRecord.amount - attackerCut;
}
}
/// Disburse liquidity stake attacks
function disburseLiqStakeAttacks(address[] memory liquidatedAccounts)
external
{
for (uint256 i = 0; liquidatedAccounts.length > i; i++) {
address liqAccount = liquidatedAccounts[i];
AccountLiqRecord storage liqAttackRecord =
stakeAttackRecords[liqAccount];
if (
block.number > liqAttackRecord.blockNum + liqStakeAttackWindow
) {
_disburseLiqAttack(liqAttackRecord);
delete stakeAttackRecords[liqAccount];
}
}
}
function liquidateFromPeg() internal returns (uint256 pegAmount) {
uint256 len = liquidationTokens.length;
for (uint256 tokenIdx = 0; len > tokenIdx; tokenIdx++) {
address buyToken = liquidationTokens[tokenIdx];
Liquidation storage liq = liquidationAmounts[buyToken];
if (liq.buy > liq.sell) {
pegAmount += PriceAware.liquidateFromPeg(
buyToken,
liq.buy - liq.sell
);
delete liquidationAmounts[buyToken];
}
}
}
function liquidateToPeg() internal returns (uint256 pegAmount) {
uint256 len = liquidationTokens.length;
for (uint256 tokenIndex = 0; len > tokenIndex; tokenIndex++) {
address token = liquidationTokens[tokenIndex];
Liquidation storage liq = liquidationAmounts[token];
if (liq.sell > liq.buy) {
uint256 sellAmount = liq.sell - liq.buy;
pegAmount += PriceAware.liquidateToPeg(token, sellAmount);
delete liquidationAmounts[token];
}
}
}
function maintainerIsFailing() internal view returns (bool) {
(address currentMaintainer, ) =
Admin(admin()).viewCurrentMaintenanceStaker();
return
maintenanceFailures[currentMaintainer] >
failureThreshold * avgLiquidationPerCall;
}
/// called by maintenance stakers to liquidate accounts below liquidation threshold
function liquidate(address[] memory liquidationCandidates)
external
noIntermediary
returns (uint256 maintainerCut)
{
bool isAuthorized = Admin(admin()).isAuthorizedStaker(msg.sender);
bool canTakeNow = isAuthorized || maintainerIsFailing();
// calcLiquidationAmounts does a lot of the work here
// * aggregates both sell and buy side targets to be liquidated
// * returns attacker cuts to them
// * aggregates any returned fees from unauthorized (attacking) attempts
maintainerCut = calcLiquidationAmounts(
liquidationCandidates,
isAuthorized
);
uint256 sale2pegAmount = liquidateToPeg();
uint256 peg2targetCost = liquidateFromPeg();
delete liquidationTokens;
// this may be a bit imprecise, since individual shortfalls may be obscured
// by overall returns and the maintainer cut is taken out of the net total,
// but it gives us the general picture
uint256 costWithCut =
(peg2targetCost * (100 + MAINTAINER_CUT_PERCENT)) / 100;
if (costWithCut > sale2pegAmount) {
emit LiquidationShortfall(costWithCut - sale2pegAmount);
canTakeNow =
canTakeNow &&
IERC20(peg).balanceOf(fund()) > costWithCut;
}
address loser = address(0);
if (!canTakeNow) {
// whoever is the current responsible maintenance staker
// and liable to lose their stake
loser = Admin(admin()).getUpdatedCurrentStaker();
}
// iterate over traders and send back their money
// as well as giving attackers their due, in case caller isn't authorized
for (
uint256 traderIdx = 0;
tradersToLiquidate.length > traderIdx;
traderIdx++
) {
address traderAddress = tradersToLiquidate[traderIdx];
CrossMarginAccount storage account = marginAccounts[traderAddress];
uint256 holdingsValue = holdingsInPeg(account);
uint256 borrowValue = loanInPeg(account);
// 5% of value borrowed
uint256 maintainerCut4Account =
(borrowValue * MAINTAINER_CUT_PERCENT) / 100;
maintainerCut += maintainerCut4Account;
if (!canTakeNow) {
// This could theoretically lead to a previous attackers
// record being overwritten, but only if the trader restarts
// their account and goes back into the red within the short time window
// which would be a costly attack requiring collusion without upside
AccountLiqRecord storage liqAttackRecord =
stakeAttackRecords[traderAddress];
liqAttackRecord.amount = maintainerCut4Account;
liqAttackRecord.stakeAttacker = msg.sender;
liqAttackRecord.blockNum = block.number;
liqAttackRecord.loser = loser;
}
// send back trader money
// include 1% for protocol
uint256 forfeited =
maintainerCut4Account + (borrowValue * 101) / 100;
if (holdingsValue > forfeited) {
// send remaining funds back to trader
Fund(fund()).withdraw(
PriceAware.peg,
traderAddress,
holdingsValue - forfeited
);
}
emit AccountLiquidated(traderAddress);
deleteAccount(account);
}
avgLiquidationPerCall =
(avgLiquidationPerCall * 99 + maintainerCut) /
100;
if (canTakeNow) {
Fund(fund()).withdraw(PriceAware.peg, msg.sender, maintainerCut);
}
address currentMaintainer = Admin(admin()).getUpdatedCurrentStaker();
if (isAuthorized) {
if (maintenanceFailures[currentMaintainer] > maintainerCut) {
maintenanceFailures[currentMaintainer] -= maintainerCut;
} else {
maintenanceFailures[currentMaintainer] = 0;
}
} else {
maintenanceFailures[currentMaintainer] += maintainerCut;
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./Fund.sol";
import "./Lending.sol";
import "./RoleAware.sol";
import "./CrossMarginLiquidation.sol";
// Goal: all external functions only accessible to margintrader role
// except for view functions of course
contract CrossMarginTrading is CrossMarginLiquidation, IMarginTrading {
constructor(address _peg, address _roles)
RoleAware(_roles)
PriceAware(_peg)
{}
/// @dev admin function to set the token cap
function setTokenCap(address token, uint256 cap)
external
onlyOwnerExecActivator
{
tokenCaps[token] = cap;
}
/// @dev setter for cooling off period for withdrawing funds after deposit
function setCoolingOffPeriod(uint256 blocks) external onlyOwnerExec {
coolingOffPeriod = blocks;
}
/// @dev admin function to set leverage
function setLeveragePercent(uint256 _leveragePercent)
external
onlyOwnerExec
{
leveragePercent = _leveragePercent;
}
/// @dev admin function to set liquidation threshold
function setLiquidationThresholdPercent(uint256 threshold)
external
onlyOwnerExec
{
liquidationThresholdPercent = threshold;
}
/// @dev gets called by router to affirm a deposit to an account
function registerDeposit(
address trader,
address token,
uint256 depositAmount
) external override returns (uint256 extinguishableDebt) {
require(isMarginTrader(msg.sender), "Calling contr. not authorized");
CrossMarginAccount storage account = marginAccounts[trader];
account.lastDepositBlock = block.number;
if (account.borrowed[token] > 0) {
extinguishableDebt = min(depositAmount, account.borrowed[token]);
extinguishDebt(account, token, extinguishableDebt);
totalShort[token] -= extinguishableDebt;
}
// no overflow because depositAmount >= extinguishableDebt
uint256 addedHolding = depositAmount - extinguishableDebt;
_registerDeposit(account, token, addedHolding);
}
function _registerDeposit(
CrossMarginAccount storage account,
address token,
uint256 addedHolding
) internal {
addHolding(account, token, addedHolding);
totalLong[token] += addedHolding;
require(
tokenCaps[token] >= totalLong[token],
"Exceeds global token cap"
);
}
/// @dev gets called by router to affirm borrowing event
function registerBorrow(
address trader,
address borrowToken,
uint256 borrowAmount
) external override {
require(isMarginTrader(msg.sender), "Calling contr. not authorized");
CrossMarginAccount storage account = marginAccounts[trader];
addHolding(account, borrowToken, borrowAmount);
_registerBorrow(account, borrowToken, borrowAmount);
}
function _registerBorrow(
CrossMarginAccount storage account,
address borrowToken,
uint256 borrowAmount
) internal {
totalShort[borrowToken] += borrowAmount;
totalLong[borrowToken] += borrowAmount;
require(
tokenCaps[borrowToken] >= totalShort[borrowToken] &&
tokenCaps[borrowToken] >= totalLong[borrowToken],
"Exceeds global token cap"
);
borrow(account, borrowToken, borrowAmount);
}
/// @dev gets called by router to affirm withdrawal of tokens from account
function registerWithdrawal(
address trader,
address withdrawToken,
uint256 withdrawAmount
) external override {
require(isMarginTrader(msg.sender), "Calling contr not authorized");
CrossMarginAccount storage account = marginAccounts[trader];
_registerWithdrawal(account, withdrawToken, withdrawAmount);
}
function _registerWithdrawal(
CrossMarginAccount storage account,
address withdrawToken,
uint256 withdrawAmount
) internal {
require(
block.number > account.lastDepositBlock + coolingOffPeriod,
"No withdrawal soon after deposit"
);
totalLong[withdrawToken] -= withdrawAmount;
// throws on underflow
account.holdings[withdrawToken] =
account.holdings[withdrawToken] -
withdrawAmount;
require(positiveBalance(account), "Insufficient balance");
}
/// @dev overcollateralized borrowing on a cross margin account, called by router
function registerOvercollateralizedBorrow(
address trader,
address depositToken,
uint256 depositAmount,
address borrowToken,
uint256 withdrawAmount
) external override {
require(isMarginTrader(msg.sender), "Calling contr. not authorized");
CrossMarginAccount storage account = marginAccounts[trader];
_registerDeposit(account, depositToken, depositAmount);
_registerBorrow(account, borrowToken, withdrawAmount);
_registerWithdrawal(account, borrowToken, withdrawAmount);
account.lastDepositBlock = block.number;
}
/// @dev gets called by router to register a trade and borrow and extinguish as necessary
function registerTradeAndBorrow(
address trader,
address tokenFrom,
address tokenTo,
uint256 inAmount,
uint256 outAmount
)
external
override
returns (uint256 extinguishableDebt, uint256 borrowAmount)
{
require(isMarginTrader(msg.sender), "Calling contr. not an authorized");
CrossMarginAccount storage account = marginAccounts[trader];
if (account.borrowed[tokenTo] > 0) {
extinguishableDebt = min(outAmount, account.borrowed[tokenTo]);
extinguishDebt(account, tokenTo, extinguishableDebt);
totalShort[tokenTo] -= extinguishableDebt;
}
uint256 sellAmount = inAmount;
uint256 fromHoldings = account.holdings[tokenFrom];
if (inAmount > fromHoldings) {
sellAmount = fromHoldings;
/// won't overflow
borrowAmount = inAmount - sellAmount;
}
if (inAmount > borrowAmount) {
totalLong[tokenFrom] -= inAmount - borrowAmount;
}
if (outAmount > extinguishableDebt) {
totalLong[tokenTo] += outAmount - extinguishableDebt;
}
require(
tokenCaps[tokenTo] >= totalLong[tokenTo],
"Exceeds global token cap"
);
adjustAmounts(
account,
tokenFrom,
tokenTo,
sellAmount,
outAmount - extinguishableDebt
);
if (borrowAmount > 0) {
totalShort[tokenFrom] += borrowAmount;
require(
tokenCaps[tokenFrom] >= totalShort[tokenFrom],
"Exceeds global token cap"
);
borrow(account, tokenFrom, borrowAmount);
}
}
/// @dev can get called by router to register the dissolution of an account
function registerLiquidation(address trader) external override {
require(isMarginTrader(msg.sender), "Calling contr. not authorized");
CrossMarginAccount storage account = marginAccounts[trader];
require(loanInPeg(account) == 0, "Can't liquidate: borrowing");
deleteAccount(account);
}
/// @dev currently holding in this token
function viewBalanceInToken(address trader, address token)
external
view
returns (uint256)
{
CrossMarginAccount storage account = marginAccounts[trader];
return account.holdings[token];
}
/// @dev view function to display account held assets state
function getHoldingAmounts(address trader)
external
view
override
returns (
address[] memory holdingTokens,
uint256[] memory holdingAmounts
)
{
CrossMarginAccount storage account = marginAccounts[trader];
holdingTokens = account.holdingTokens;
holdingAmounts = new uint256[](account.holdingTokens.length);
for (uint256 idx = 0; holdingTokens.length > idx; idx++) {
address tokenAddress = holdingTokens[idx];
holdingAmounts[idx] = account.holdings[tokenAddress];
}
}
/// @dev view function to display account borrowing state
function getBorrowAmounts(address trader)
external
view
override
returns (address[] memory borrowTokens, uint256[] memory borrowAmounts)
{
CrossMarginAccount storage account = marginAccounts[trader];
borrowTokens = account.borrowTokens;
borrowAmounts = new uint256[](account.borrowTokens.length);
for (uint256 idx = 0; borrowTokens.length > idx; idx++) {
address tokenAddress = borrowTokens[idx];
borrowAmounts[idx] = Lending(lending()).viewWithBorrowInterest(
account.borrowed[tokenAddress],
tokenAddress,
account.borrowedYieldQuotientsFP[tokenAddress]
);
}
}
/// @dev view function to get loan amount in peg
function viewLoanInPeg(address trader)
external
view
returns (uint256 amount)
{
CrossMarginAccount storage account = marginAccounts[trader];
return
viewTokensInPegWithYield(
account.borrowTokens,
account.borrowed,
account.borrowedYieldQuotientsFP
);
}
/// @dev total of assets of account, expressed in reference currency
function viewHoldingsInPeg(address trader) external view returns (uint256) {
CrossMarginAccount storage account = marginAccounts[trader];
return viewTokensInPeg(account.holdingTokens, account.holdings);
}
/// @dev can this trader be liquidated?
function canBeLiquidated(address trader) external view returns (bool) {
CrossMarginAccount storage account = marginAccounts[trader];
uint256 loan =
viewTokensInPegWithYield(
account.borrowTokens,
account.borrowed,
account.borrowedYieldQuotientsFP
);
uint256 holdings =
viewTokensInPeg(account.holdingTokens, account.holdings);
return liquidationThresholdPercent * loan >= 100 * holdings;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/IWETH.sol";
import "./RoleAware.sol";
/// @title Manage funding
contract Fund is RoleAware {
using SafeERC20 for IERC20;
/// wrapped ether
address public immutable WETH;
constructor(address _WETH, address _roles) RoleAware(_roles) {
WETH = _WETH;
}
/// Deposit an active token
function deposit(address depositToken, uint256 depositAmount) external {
IERC20(depositToken).safeTransferFrom(
msg.sender,
address(this),
depositAmount
);
}
/// Deposit token on behalf of `sender`
function depositFor(
address sender,
address depositToken,
uint256 depositAmount
) external {
require(isFundTransferer(msg.sender), "Unauthorized deposit");
IERC20(depositToken).safeTransferFrom(
sender,
address(this),
depositAmount
);
}
/// Deposit to wrapped ether
function depositToWETH() external payable {
IWETH(WETH).deposit{value: msg.value}();
}
// withdrawers role
function withdraw(
address withdrawalToken,
address recipient,
uint256 withdrawalAmount
) external {
require(isFundTransferer(msg.sender), "Unauthorized withdraw");
IERC20(withdrawalToken).safeTransfer(recipient, withdrawalAmount);
}
// withdrawers role
function withdrawETH(address recipient, uint256 withdrawalAmount) external {
require(isFundTransferer(msg.sender), "Unauthorized withdraw");
IWETH(WETH).withdraw(withdrawalAmount);
Address.sendValue(payable(recipient), withdrawalAmount);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "./BaseLending.sol";
struct HourlyBond {
uint256 amount;
uint256 yieldQuotientFP;
uint256 moduloHour;
}
/// @title Here we offer subscriptions to auto-renewing hourly bonds
/// Funds are locked in for an 50 minutes per hour, while interest rates float
abstract contract HourlyBondSubscriptionLending is BaseLending {
mapping(address => YieldAccumulator) hourlyBondYieldAccumulators;
uint256 constant RATE_UPDATE_WINDOW = 10 minutes;
uint256 public withdrawalWindow = 20 minutes;
uint256 constant MAX_HOUR_UPDATE = 4;
// issuer => holder => bond record
mapping(address => mapping(address => HourlyBond))
public hourlyBondAccounts;
uint256 public borrowingFactorPercent = 200;
uint256 constant borrowMinAPR = 6;
uint256 constant borrowMinHourlyYield =
FP48 + (borrowMinAPR * FP48) / 100 / hoursPerYear;
function _makeHourlyBond(
address issuer,
address holder,
uint256 amount
) internal {
HourlyBond storage bond = hourlyBondAccounts[issuer][holder];
updateHourlyBondAmount(issuer, bond);
YieldAccumulator storage yieldAccumulator =
hourlyBondYieldAccumulators[issuer];
bond.yieldQuotientFP = yieldAccumulator.accumulatorFP;
if (bond.amount == 0) {
bond.moduloHour = block.timestamp % (1 hours);
}
bond.amount += amount;
lendingMeta[issuer].totalLending += amount;
}
function updateHourlyBondAmount(address issuer, HourlyBond storage bond)
internal
{
uint256 yieldQuotientFP = bond.yieldQuotientFP;
if (yieldQuotientFP > 0) {
YieldAccumulator storage yA =
getUpdatedHourlyYield(
issuer,
hourlyBondYieldAccumulators[issuer],
RATE_UPDATE_WINDOW
);
uint256 oldAmount = bond.amount;
bond.amount = applyInterest(
bond.amount,
yA.accumulatorFP,
yieldQuotientFP
);
uint256 deltaAmount = bond.amount - oldAmount;
lendingMeta[issuer].totalLending += deltaAmount;
}
}
// Retrieves bond balance for issuer and holder
function viewHourlyBondAmount(address issuer, address holder)
public
view
returns (uint256)
{
HourlyBond storage bond = hourlyBondAccounts[issuer][holder];
uint256 yieldQuotientFP = bond.yieldQuotientFP;
uint256 cumulativeYield =
viewCumulativeYieldFP(
hourlyBondYieldAccumulators[issuer],
block.timestamp
);
if (yieldQuotientFP > 0) {
return applyInterest(bond.amount, cumulativeYield, yieldQuotientFP);
} else {
return bond.amount;
}
}
function _withdrawHourlyBond(
address issuer,
HourlyBond storage bond,
uint256 amount
) internal {
// how far the current hour has advanced (relative to acccount hourly clock)
uint256 currentOffset = (block.timestamp - bond.moduloHour) % (1 hours);
require(
withdrawalWindow >= currentOffset,
"Tried withdrawing outside subscription cancellation time window"
);
bond.amount -= amount;
lendingMeta[issuer].totalLending -= amount;
}
function calcCumulativeYieldFP(
YieldAccumulator storage yieldAccumulator,
uint256 timeDelta
) internal view returns (uint256 accumulatorFP) {
uint256 secondsDelta = timeDelta % (1 hours);
// linearly interpolate interest for seconds
// FP * FP * 1 / (FP * 1) = FP
accumulatorFP =
yieldAccumulator.accumulatorFP +
(yieldAccumulator.accumulatorFP *
(yieldAccumulator.hourlyYieldFP - FP48) *
secondsDelta) /
(FP48 * 1 hours);
uint256 hoursDelta = timeDelta / (1 hours);
if (hoursDelta > 0) {
uint256 accumulatorBeforeFP = accumulatorFP;
for (uint256 i = 0; hoursDelta > i && MAX_HOUR_UPDATE > i; i++) {
// FP48 * FP48 / FP48 = FP48
accumulatorFP =
(accumulatorFP * yieldAccumulator.hourlyYieldFP) /
FP48;
}
// a lot of time has passed
if (hoursDelta > MAX_HOUR_UPDATE) {
// apply interest in non-compounding way
accumulatorFP +=
((accumulatorFP - accumulatorBeforeFP) *
(hoursDelta - MAX_HOUR_UPDATE)) /
MAX_HOUR_UPDATE;
}
}
}
/// @dev updates yield accumulators for both borrowing and lending
/// issuer address represents a token
function updateHourlyYield(address issuer)
public
returns (uint256 hourlyYield)
{
return
getUpdatedHourlyYield(
issuer,
hourlyBondYieldAccumulators[issuer],
RATE_UPDATE_WINDOW
)
.hourlyYieldFP;
}
/// @dev updates yield accumulators for both borrowing and lending
function getUpdatedHourlyYield(
address issuer,
YieldAccumulator storage accumulator,
uint256 window
) internal returns (YieldAccumulator storage) {
uint256 lastUpdated = accumulator.lastUpdated;
uint256 timeDelta = (block.timestamp - lastUpdated);
if (timeDelta > window) {
YieldAccumulator storage borrowAccumulator =
borrowYieldAccumulators[issuer];
accumulator.accumulatorFP = calcCumulativeYieldFP(
accumulator,
timeDelta
);
LendingMetadata storage meta = lendingMeta[issuer];
accumulator.hourlyYieldFP = currentLendingRateFP(
meta.totalLending,
meta.totalBorrowed
);
accumulator.lastUpdated = block.timestamp;
updateBorrowYieldAccu(borrowAccumulator);
borrowAccumulator.hourlyYieldFP = max(
borrowMinHourlyYield,
FP48 +
(borrowingFactorPercent *
(accumulator.hourlyYieldFP - FP48)) /
100
);
}
return accumulator;
}
function updateBorrowYieldAccu(YieldAccumulator storage borrowAccumulator)
internal
{
uint256 timeDelta = block.timestamp - borrowAccumulator.lastUpdated;
if (timeDelta > RATE_UPDATE_WINDOW) {
borrowAccumulator.accumulatorFP = calcCumulativeYieldFP(
borrowAccumulator,
timeDelta
);
borrowAccumulator.lastUpdated = block.timestamp;
}
}
function getUpdatedBorrowYieldAccuFP(address issuer)
external
returns (uint256)
{
YieldAccumulator storage yA = borrowYieldAccumulators[issuer];
updateBorrowYieldAccu(yA);
return yA.accumulatorFP;
}
function viewCumulativeYieldFP(
YieldAccumulator storage yA,
uint256 timestamp
) internal view returns (uint256) {
uint256 timeDelta = (timestamp - yA.lastUpdated);
if (timeDelta > RATE_UPDATE_WINDOW) {
return calcCumulativeYieldFP(yA, timeDelta);
} else {
return yA.accumulatorFP;
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "./Fund.sol";
import "./HourlyBondSubscriptionLending.sol";
import "../libraries/IncentiveReporter.sol";
// TODO activate bonds for lending
/// @title Manage lending for a variety of bond issuers
contract Lending is RoleAware, HourlyBondSubscriptionLending {
/// mapping issuers to tokens
/// (in crossmargin, the issuers are tokens themselves)
mapping(address => address) public issuerTokens;
/// In case of shortfall, adjust debt
mapping(address => uint256) public haircuts;
/// map of available issuers
mapping(address => bool) public activeIssuers;
uint256 constant BORROW_RATE_UPDATE_WINDOW = 60 minutes;
constructor(address _roles) RoleAware(_roles) {}
/// Make a issuer available for protocol
function activateIssuer(address issuer) external {
activateIssuer(issuer, issuer);
}
/// Make issuer != token available for protocol (isol. margin)
function activateIssuer(address issuer, address token)
public
onlyOwnerExecActivator
{
activeIssuers[issuer] = true;
issuerTokens[issuer] = token;
}
/// Remove a issuer from trading availability
function deactivateIssuer(address issuer) external onlyOwnerExecActivator {
activeIssuers[issuer] = false;
}
/// Set lending cap
function setLendingCap(address issuer, uint256 cap)
external
onlyOwnerExecActivator
{
lendingMeta[issuer].lendingCap = cap;
}
/// Set withdrawal window
function setWithdrawalWindow(uint256 window) external onlyOwnerExec {
withdrawalWindow = window;
}
function setNormalRatePerPercent(uint256 rate) external onlyOwnerExec {
normalRatePerPercent = rate;
}
function setHighRatePerPercent(uint256 rate) external onlyOwnerExec {
highRatePerPercent = rate;
}
/// Set hourly yield APR for issuer
function setHourlyYieldAPR(address issuer, uint256 aprPercent)
external
onlyOwnerExecActivator
{
YieldAccumulator storage yieldAccumulator =
hourlyBondYieldAccumulators[issuer];
if (yieldAccumulator.accumulatorFP == 0) {
uint256 yieldFP = FP48 + (FP48 * aprPercent) / 100 / (24 * 365);
hourlyBondYieldAccumulators[issuer] = YieldAccumulator({
accumulatorFP: FP48,
lastUpdated: block.timestamp,
hourlyYieldFP: yieldFP
});
} else {
YieldAccumulator storage yA =
getUpdatedHourlyYield(
issuer,
yieldAccumulator,
RATE_UPDATE_WINDOW
);
yA.hourlyYieldFP = (FP48 * (100 + aprPercent)) / 100 / (24 * 365);
}
}
/// @dev how much interest has accrued to a borrowed balance over time
function applyBorrowInterest(
uint256 balance,
address issuer,
uint256 yieldQuotientFP
) external returns (uint256 balanceWithInterest, uint256 accumulatorFP) {
require(isBorrower(msg.sender), "Not approved call");
YieldAccumulator storage yA = borrowYieldAccumulators[issuer];
updateBorrowYieldAccu(yA);
accumulatorFP = yA.accumulatorFP;
balanceWithInterest = applyInterest(
balance,
accumulatorFP,
yieldQuotientFP
);
uint256 deltaAmount = balanceWithInterest - balance;
LendingMetadata storage meta = lendingMeta[issuer];
meta.totalBorrowed += deltaAmount;
}
/// @dev view function to get balance with borrowing interest applied
function viewWithBorrowInterest(
uint256 balance,
address issuer,
uint256 yieldQuotientFP
) external view returns (uint256) {
uint256 accumulatorFP =
viewCumulativeYieldFP(
borrowYieldAccumulators[issuer],
block.timestamp
);
return applyInterest(balance, accumulatorFP, yieldQuotientFP);
}
/// @dev gets called by router to register if a trader borrows issuers
function registerBorrow(address issuer, uint256 amount) external {
require(isBorrower(msg.sender), "Not approved borrower");
require(activeIssuers[issuer], "Not approved issuer");
LendingMetadata storage meta = lendingMeta[issuer];
meta.totalBorrowed += amount;
getUpdatedHourlyYield(
issuer,
hourlyBondYieldAccumulators[issuer],
BORROW_RATE_UPDATE_WINDOW
);
require(
meta.totalLending >= meta.totalBorrowed,
"Insufficient lending"
);
}
/// @dev gets called when external sources provide lending
function registerLend(address issuer, uint256 amount) external {
require(isLender(msg.sender), "Not an approved lender");
require(activeIssuers[issuer], "Not approved issuer");
LendingMetadata storage meta = lendingMeta[issuer];
meta.totalLending += amount;
getUpdatedHourlyYield(
issuer,
hourlyBondYieldAccumulators[issuer],
RATE_UPDATE_WINDOW
);
}
/// @dev gets called when external sources pay withdraw their bobnd
function registerWithdrawal(address issuer, uint256 amount) external {
require(isLender(msg.sender), "Not an approved lender");
require(activeIssuers[issuer], "Not approved issuer");
LendingMetadata storage meta = lendingMeta[issuer];
meta.totalLending -= amount;
getUpdatedHourlyYield(
issuer,
hourlyBondYieldAccumulators[issuer],
RATE_UPDATE_WINDOW
);
}
/// @dev gets called by router if loan is extinguished
function payOff(address issuer, uint256 amount) external {
require(isBorrower(msg.sender), "Not approved borrower");
lendingMeta[issuer].totalBorrowed -= amount;
}
/// @dev get the borrow yield for a specific issuer/token
function viewAccumulatedBorrowingYieldFP(address issuer)
external
view
returns (uint256)
{
YieldAccumulator storage yA = borrowYieldAccumulators[issuer];
return viewCumulativeYieldFP(yA, block.timestamp);
}
function viewAPRPer10k(YieldAccumulator storage yA)
internal
view
returns (uint256)
{
uint256 hourlyYieldFP = yA.hourlyYieldFP;
uint256 aprFP =
((hourlyYieldFP * 10_000 - FP48 * 10_000) * 365 days) / (1 hours);
return aprFP / FP48;
}
/// @dev get current borrowing interest per 10k for a token / issuer
function viewBorrowAPRPer10k(address issuer)
external
view
returns (uint256)
{
return viewAPRPer10k(borrowYieldAccumulators[issuer]);
}
/// @dev get current lending APR per 10k for a token / issuer
function viewHourlyBondAPRPer10k(address issuer)
external
view
returns (uint256)
{
return viewAPRPer10k(hourlyBondYieldAccumulators[issuer]);
}
/// @dev In a liquidity crunch make a fallback bond until liquidity is good again
function makeFallbackBond(
address issuer,
address holder,
uint256 amount
) external {
require(isLender(msg.sender), "Not an approved lender");
_makeHourlyBond(issuer, holder, amount);
}
/// @dev withdraw an hour bond
function withdrawHourlyBond(address issuer, uint256 amount) external {
HourlyBond storage bond = hourlyBondAccounts[issuer][msg.sender];
// apply all interest
updateHourlyBondAmount(issuer, bond);
super._withdrawHourlyBond(issuer, bond, amount);
if (bond.amount == 0) {
delete hourlyBondAccounts[issuer][msg.sender];
}
disburse(issuer, msg.sender, amount);
IncentiveReporter.subtractFromClaimAmount(issuer, msg.sender, amount);
}
/// Shut down hourly bond account for `issuer`
function closeHourlyBondAccount(address issuer) external {
HourlyBond storage bond = hourlyBondAccounts[issuer][msg.sender];
// apply all interest
updateHourlyBondAmount(issuer, bond);
uint256 amount = bond.amount;
super._withdrawHourlyBond(issuer, bond, amount);
disburse(issuer, msg.sender, amount);
delete hourlyBondAccounts[issuer][msg.sender];
IncentiveReporter.subtractFromClaimAmount(issuer, msg.sender, amount);
}
/// @dev buy hourly bond subscription
function buyHourlyBondSubscription(address issuer, uint256 amount)
external
{
require(activeIssuers[issuer], "Not approved issuer");
collectToken(issuer, msg.sender, amount);
super._makeHourlyBond(issuer, msg.sender, amount);
IncentiveReporter.addToClaimAmount(issuer, msg.sender, amount);
}
function initBorrowYieldAccumulator(address issuer)
external
onlyOwnerExecActivator
{
YieldAccumulator storage yA = borrowYieldAccumulators[issuer];
require(yA.accumulatorFP == 0, "don't re-initialize");
yA.accumulatorFP = FP48;
yA.lastUpdated = block.timestamp;
yA.hourlyYieldFP = FP48 + (FP48 * borrowMinAPR) / 100 / (365 * 24);
}
function setBorrowingFactorPercent(uint256 borrowingFactor)
external
onlyOwnerExec
{
borrowingFactorPercent = borrowingFactor;
}
function issuanceBalance(address issuer)
internal
view
override
returns (uint256)
{
address token = issuerTokens[issuer];
if (token == issuer) {
// cross margin
return IERC20(token).balanceOf(fund());
} else {
return lendingMeta[issuer].totalLending - haircuts[issuer];
}
}
function disburse(
address issuer,
address recipient,
uint256 amount
) internal {
uint256 haircutAmount = haircuts[issuer];
if (haircutAmount > 0 && amount > 0) {
uint256 totalLending = lendingMeta[issuer].totalLending;
uint256 adjustment =
(amount * min(totalLending, haircutAmount)) / totalLending;
amount = amount - adjustment;
haircuts[issuer] -= adjustment;
}
address token = issuerTokens[issuer];
Fund(fund()).withdraw(token, recipient, amount);
}
function collectToken(
address issuer,
address source,
uint256 amount
) internal {
Fund(fund()).depositFor(source, issuer, amount);
}
function haircut(uint256 amount) external {
haircuts[msg.sender] += amount;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "./RoleAware.sol";
import "../interfaces/IMarginTrading.sol";
import "./Lending.sol";
import "./Admin.sol";
import "./BaseRouter.sol";
import "../libraries/IncentiveReporter.sol";
/// @title Top level transaction controller
contract MarginRouter is RoleAware, BaseRouter {
event AccountUpdated(address indexed trader);
uint256 public constant mswapFeesPer10k = 10;
address public immutable WETH;
constructor(address _WETH, address _roles) RoleAware(_roles) {
WETH = _WETH;
}
///////////////////////////
// Cross margin endpoints
///////////////////////////
/// @notice traders call this to deposit funds on cross margin
function crossDeposit(address depositToken, uint256 depositAmount)
external
{
Fund(fund()).depositFor(msg.sender, depositToken, depositAmount);
uint256 extinguishAmount =
IMarginTrading(crossMarginTrading()).registerDeposit(
msg.sender,
depositToken,
depositAmount
);
if (extinguishAmount > 0) {
Lending(lending()).payOff(depositToken, extinguishAmount);
IncentiveReporter.subtractFromClaimAmount(
depositToken,
msg.sender,
extinguishAmount
);
}
emit AccountUpdated(msg.sender);
}
/// @notice deposit wrapped ehtereum into cross margin account
function crossDepositETH() external payable {
Fund(fund()).depositToWETH{value: msg.value}();
uint256 extinguishAmount =
IMarginTrading(crossMarginTrading()).registerDeposit(
msg.sender,
WETH,
msg.value
);
if (extinguishAmount > 0) {
Lending(lending()).payOff(WETH, extinguishAmount);
IncentiveReporter.subtractFromClaimAmount(
WETH,
msg.sender,
extinguishAmount
);
}
emit AccountUpdated(msg.sender);
}
/// @notice withdraw deposits/earnings from cross margin account
function crossWithdraw(address withdrawToken, uint256 withdrawAmount)
external
{
IMarginTrading(crossMarginTrading()).registerWithdrawal(
msg.sender,
withdrawToken,
withdrawAmount
);
Fund(fund()).withdraw(withdrawToken, msg.sender, withdrawAmount);
emit AccountUpdated(msg.sender);
}
/// @notice withdraw ethereum from cross margin account
function crossWithdrawETH(uint256 withdrawAmount) external {
IMarginTrading(crossMarginTrading()).registerWithdrawal(
msg.sender,
WETH,
withdrawAmount
);
Fund(fund()).withdrawETH(msg.sender, withdrawAmount);
emit AccountUpdated(msg.sender);
}
/// @notice borrow into cross margin trading account
function crossBorrow(address borrowToken, uint256 borrowAmount) external {
Lending(lending()).registerBorrow(borrowToken, borrowAmount);
IMarginTrading(crossMarginTrading()).registerBorrow(
msg.sender,
borrowToken,
borrowAmount
);
IncentiveReporter.addToClaimAmount(
borrowToken,
msg.sender,
borrowAmount
);
emit AccountUpdated(msg.sender);
}
/// @notice convenience function to perform overcollateralized borrowing
/// against a cross margin account.
/// @dev caution: the account still has to have a positive balaance at the end
/// of the withdraw. So an underwater account may not be able to withdraw
function crossOvercollateralizedBorrow(
address depositToken,
uint256 depositAmount,
address borrowToken,
uint256 withdrawAmount
) external {
Fund(fund()).depositFor(msg.sender, depositToken, depositAmount);
Lending(lending()).registerBorrow(borrowToken, withdrawAmount);
IMarginTrading(crossMarginTrading()).registerOvercollateralizedBorrow(
msg.sender,
depositToken,
depositAmount,
borrowToken,
withdrawAmount
);
Fund(fund()).withdraw(borrowToken, msg.sender, withdrawAmount);
IncentiveReporter.addToClaimAmount(
borrowToken,
msg.sender,
withdrawAmount
);
emit AccountUpdated(msg.sender);
}
/// @notice close an account that is no longer borrowing and return gains
function crossCloseAccount() external {
(address[] memory holdingTokens, uint256[] memory holdingAmounts) =
IMarginTrading(crossMarginTrading()).getHoldingAmounts(msg.sender);
// requires all debts paid off
IMarginTrading(crossMarginTrading()).registerLiquidation(msg.sender);
for (uint256 i; holdingTokens.length > i; i++) {
Fund(fund()).withdraw(
holdingTokens[i],
msg.sender,
holdingAmounts[i]
);
}
emit AccountUpdated(msg.sender);
}
/// @notice entry point for swapping tokens held in cross margin account
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
bytes32 amms,
address[] calldata tokens,
uint256 deadline
) external ensure(deadline) returns (uint256[] memory amounts) {
// calc fees
uint256 fees = takeFeesFromInput(amountIn);
address[] memory pairs;
(amounts, pairs) = UniswapStyleLib.getAmountsOut(
amountIn - fees,
amms,
tokens
);
// checks that trader is within allowed lending bounds
registerTrade(
msg.sender,
tokens[0],
tokens[tokens.length - 1],
amountIn,
amounts[amounts.length - 1]
);
_fundSwapExactT4T(amounts, amountOutMin, pairs, tokens);
}
/// @notice entry point for swapping tokens held in cross margin account
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
bytes32 amms,
address[] calldata tokens,
uint256 deadline
) external ensure(deadline) returns (uint256[] memory amounts) {
address[] memory pairs;
(amounts, pairs) = UniswapStyleLib.getAmountsIn(
amountOut + takeFeesFromOutput(amountOut),
amms,
tokens
);
// checks that trader is within allowed lending bounds
registerTrade(
msg.sender,
tokens[0],
tokens[tokens.length - 1],
amounts[0],
amountOut
);
_fundSwapT4ExactT(amounts, amountInMax, pairs, tokens);
}
/// @dev helper function does all the work of telling other contracts
/// about a cross margin trade
function registerTrade(
address trader,
address inToken,
address outToken,
uint256 inAmount,
uint256 outAmount
) internal {
(uint256 extinguishAmount, uint256 borrowAmount) =
IMarginTrading(crossMarginTrading()).registerTradeAndBorrow(
trader,
inToken,
outToken,
inAmount,
outAmount
);
if (extinguishAmount > 0) {
Lending(lending()).payOff(outToken, extinguishAmount);
IncentiveReporter.subtractFromClaimAmount(
outToken,
trader,
extinguishAmount
);
}
if (borrowAmount > 0) {
Lending(lending()).registerBorrow(inToken, borrowAmount);
IncentiveReporter.addToClaimAmount(inToken, trader, borrowAmount);
}
emit AccountUpdated(trader);
}
/////////////
// Helpers
/////////////
/// @dev internal helper swapping exact token for token on AMM
function _fundSwapExactT4T(
uint256[] memory amounts,
uint256 amountOutMin,
address[] memory pairs,
address[] calldata tokens
) internal {
require(
amounts[amounts.length - 1] >= amountOutMin,
"MarginRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
Fund(fund()).withdraw(tokens[0], pairs[0], amounts[0]);
_swap(amounts, pairs, tokens, fund());
}
/// @notice make swaps on AMM using protocol funds, only for authorized contracts
function authorizedSwapExactT4T(
uint256 amountIn,
uint256 amountOutMin,
bytes32 amms,
address[] calldata tokens
) external returns (uint256[] memory amounts) {
require(
isAuthorizedFundTrader(msg.sender),
"Calling contract is not authorized to trade with protocl funds"
);
address[] memory pairs;
(amounts, pairs) = UniswapStyleLib.getAmountsOut(
amountIn,
amms,
tokens
);
_fundSwapExactT4T(amounts, amountOutMin, pairs, tokens);
}
// @dev internal helper swapping exact token for token on on AMM
function _fundSwapT4ExactT(
uint256[] memory amounts,
uint256 amountInMax,
address[] memory pairs,
address[] calldata tokens
) internal {
require(
amounts[0] <= amountInMax,
"MarginRouter: EXCESSIVE_INPUT_AMOUNT"
);
Fund(fund()).withdraw(tokens[0], pairs[0], amounts[0]);
_swap(amounts, pairs, tokens, fund());
}
//// @notice swap protocol funds on AMM, only for authorized
function authorizedSwapT4ExactT(
uint256 amountOut,
uint256 amountInMax,
bytes32 amms,
address[] calldata tokens
) external returns (uint256[] memory amounts) {
require(
isAuthorizedFundTrader(msg.sender),
"Calling contract is not authorized to trade with protocl funds"
);
address[] memory pairs;
(amounts, pairs) = UniswapStyleLib.getAmountsIn(
amountOut,
amms,
tokens
);
_fundSwapT4ExactT(amounts, amountInMax, pairs, tokens);
}
function takeFeesFromOutput(uint256 amount)
internal
pure
returns (uint256 fees)
{
fees = (mswapFeesPer10k * amount) / 10_000;
}
function takeFeesFromInput(uint256 amount)
internal
pure
returns (uint256 fees)
{
fees = (mswapFeesPer10k * amount) / (10_000 + mswapFeesPer10k);
}
function getAmountsOut(
uint256 inAmount,
bytes32 amms,
address[] calldata tokens
) external view returns (uint256[] memory amounts) {
(amounts, ) = UniswapStyleLib.getAmountsOut(inAmount, amms, tokens);
}
function getAmountsIn(
uint256 outAmount,
bytes32 amms,
address[] calldata tokens
) external view returns (uint256[] memory amounts) {
(amounts, ) = UniswapStyleLib.getAmountsIn(outAmount, amms, tokens);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "./RoleAware.sol";
import "./MarginRouter.sol";
import "../libraries/UniswapStyleLib.sol";
/// Stores how many of token you could get for 1k of peg
struct TokenPrice {
uint256 lastUpdated;
uint256 priceFP;
address[] liquidationTokens;
bytes32 amms;
address[] inverseLiquidationTokens;
bytes32 inverseAmms;
}
struct VolatilitySetting {
uint256 priceUpdateWindow;
uint256 updateRatePermil;
uint256 voluntaryUpdateWindow;
}
struct PairPrice {
uint256 cumulative;
uint256 lastUpdated;
uint256 priceFP;
}
/// @title The protocol features several mechanisms to prevent vulnerability to
/// price manipulation:
/// 1) global exposure caps on all tokens which need to be raised gradually
/// during the process of introducing a new token, making attacks unprofitable
/// due to lack of scale
/// 2) Exponential moving average with cautious price update. Prices for estimating
/// how much a trader can borrow need not be extremely current and precise, mainly
/// they must be resilient against extreme manipulation
/// 3) Liquidators may not call from a contract address, to prevent extreme forms of
/// of front-running and other price manipulation.
abstract contract PriceAware is RoleAware {
uint256 constant FP112 = 2**112;
address public immutable peg;
mapping(address => TokenPrice) public tokenPrices;
mapping(address => mapping(address => PairPrice)) public pairPrices;
/// update window in blocks
// TODO
uint256 public priceUpdateWindow = 20 minutes;
uint256 public voluntaryUpdateWindow = 5 minutes;
uint256 public UPDATE_RATE_PERMIL = 400;
VolatilitySetting[] public volatilitySettings;
constructor(address _peg) {
peg = _peg;
}
/// Set window for price updates
function setPriceUpdateWindow(uint16 window, uint256 voluntaryWindow)
external
onlyOwnerExec
{
priceUpdateWindow = window;
voluntaryUpdateWindow = voluntaryWindow;
}
/// Add a new volatility setting
function addVolatilitySetting(
uint256 _priceUpdateWindow,
uint256 _updateRatePermil,
uint256 _voluntaryUpdateWindow
) external onlyOwnerExec {
volatilitySettings.push(
VolatilitySetting({
priceUpdateWindow: _priceUpdateWindow,
updateRatePermil: _updateRatePermil,
voluntaryUpdateWindow: _voluntaryUpdateWindow
})
);
}
/// Choose a volatitlity setting
function chooseVolatilitySetting(uint256 index)
external
onlyOwnerExecDisabler
{
VolatilitySetting storage vs = volatilitySettings[index];
if (vs.updateRatePermil > 0) {
UPDATE_RATE_PERMIL = vs.updateRatePermil;
priceUpdateWindow = vs.priceUpdateWindow;
voluntaryUpdateWindow = vs.voluntaryUpdateWindow;
}
}
/// Set rate for updates
function setUpdateRate(uint256 rate) external onlyOwnerExec {
UPDATE_RATE_PERMIL = rate;
}
function getCurrentPriceInPeg(address token, uint256 inAmount)
internal
returns (uint256)
{
return getCurrentPriceInPeg(token, inAmount, false);
}
function getCurrentPriceInPeg(
address token,
uint256 inAmount,
bool voluntary
) public returns (uint256 priceInPeg) {
if (token == peg) {
return inAmount;
} else {
TokenPrice storage tokenPrice = tokenPrices[token];
uint256 timeDelta = block.timestamp - tokenPrice.lastUpdated;
if (
timeDelta > priceUpdateWindow ||
tokenPrice.priceFP == 0 ||
(voluntary && timeDelta > voluntaryUpdateWindow)
) {
// update the currently cached price
uint256 priceUpdateFP;
priceUpdateFP = getPriceByPairs(
tokenPrice.liquidationTokens,
tokenPrice.amms
);
_setPriceVal(tokenPrice, priceUpdateFP, UPDATE_RATE_PERMIL);
}
priceInPeg = (inAmount * tokenPrice.priceFP) / FP112;
}
}
/// Get view of current price of token in peg
function viewCurrentPriceInPeg(address token, uint256 inAmount)
public
view
returns (uint256 priceInPeg)
{
if (token == peg) {
return inAmount;
} else {
TokenPrice storage tokenPrice = tokenPrices[token];
uint256 priceFP = tokenPrice.priceFP;
priceInPeg = (inAmount * priceFP) / FP112;
}
}
function _setPriceVal(
TokenPrice storage tokenPrice,
uint256 updateFP,
uint256 weightPerMil
) internal {
tokenPrice.priceFP =
(tokenPrice.priceFP *
(1000 - weightPerMil) +
updateFP *
weightPerMil) /
1000;
tokenPrice.lastUpdated = block.timestamp;
}
/// add path from token to current liquidation peg
function setLiquidationPath(bytes32 amms, address[] memory tokens)
external
onlyOwnerExecActivator
{
address token = tokens[0];
if (token != peg) {
TokenPrice storage tokenPrice = tokenPrices[token];
tokenPrice.amms = amms;
tokenPrice.liquidationTokens = tokens;
tokenPrice.inverseLiquidationTokens = new address[](tokens.length);
bytes32 inverseAmms;
for (uint256 i = 0; tokens.length - 1 > i; i++) {
initPairPrice(tokens[i], tokens[i + 1], amms[i]);
bytes32 shifted =
bytes32(amms[i]) >> ((tokens.length - 2 - i) * 8);
inverseAmms = inverseAmms | shifted;
}
tokenPrice.inverseAmms = inverseAmms;
for (uint256 i = 0; tokens.length > i; i++) {
tokenPrice.inverseLiquidationTokens[i] = tokens[
tokens.length - i - 1
];
}
tokenPrice.priceFP = getPriceByPairs(tokens, amms);
tokenPrice.lastUpdated = block.timestamp;
}
}
function liquidateToPeg(address token, uint256 amount)
internal
returns (uint256)
{
if (token == peg) {
return amount;
} else {
TokenPrice storage tP = tokenPrices[token];
uint256[] memory amounts =
MarginRouter(marginRouter()).authorizedSwapExactT4T(
amount,
0,
tP.amms,
tP.liquidationTokens
);
uint256 outAmount = amounts[amounts.length - 1];
return outAmount;
}
}
function liquidateFromPeg(address token, uint256 targetAmount)
internal
returns (uint256)
{
if (token == peg) {
return targetAmount;
} else {
TokenPrice storage tP = tokenPrices[token];
uint256[] memory amounts =
MarginRouter(marginRouter()).authorizedSwapT4ExactT(
targetAmount,
type(uint256).max,
tP.amms,
tP.inverseLiquidationTokens
);
return amounts[0];
}
}
function getPriceByPairs(address[] memory tokens, bytes32 amms)
internal
returns (uint256 priceFP)
{
priceFP = FP112;
for (uint256 i; i < tokens.length - 1; i++) {
address inToken = tokens[i];
address outToken = tokens[i + 1];
address pair =
amms[i] == 0
? UniswapStyleLib.pairForUni(inToken, outToken)
: UniswapStyleLib.pairForSushi(inToken, outToken);
PairPrice storage pairPrice = pairPrices[pair][inToken];
(, , uint256 pairLastUpdated) = IUniswapV2Pair(pair).getReserves();
uint256 timeDelta = pairLastUpdated - pairPrice.lastUpdated;
if (timeDelta > voluntaryUpdateWindow) {
// we are in business
(address token0, ) =
UniswapStyleLib.sortTokens(inToken, outToken);
uint256 cumulative =
inToken == token0
? IUniswapV2Pair(pair).price0CumulativeLast()
: IUniswapV2Pair(pair).price1CumulativeLast();
uint256 pairPriceFP =
(cumulative - pairPrice.cumulative) / timeDelta;
priceFP = (priceFP * pairPriceFP) / FP112;
pairPrice.priceFP = pairPriceFP;
pairPrice.cumulative = cumulative;
pairPrice.lastUpdated = pairLastUpdated;
} else {
priceFP = (priceFP * pairPrice.priceFP) / FP112;
}
}
}
function initPairPrice(
address inToken,
address outToken,
bytes1 amm
) internal {
address pair =
amm == 0
? UniswapStyleLib.pairForUni(inToken, outToken)
: UniswapStyleLib.pairForSushi(inToken, outToken);
PairPrice storage pairPrice = pairPrices[pair][inToken];
if (pairPrice.lastUpdated == 0) {
(uint112 reserve0, uint112 reserve1, uint256 pairLastUpdated) =
IUniswapV2Pair(pair).getReserves();
(address token0, ) = UniswapStyleLib.sortTokens(inToken, outToken);
if (inToken == token0) {
pairPrice.priceFP = (FP112 * reserve1) / reserve0;
pairPrice.cumulative = IUniswapV2Pair(pair)
.price0CumulativeLast();
} else {
pairPrice.priceFP = (FP112 * reserve0) / reserve1;
pairPrice.cumulative = IUniswapV2Pair(pair)
.price1CumulativeLast();
}
pairPrice.lastUpdated = block.timestamp;
pairPrice.lastUpdated = pairLastUpdated;
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "./Roles.sol";
/// @title Role management behavior
/// Main characters are for service discovery
/// Whereas roles are for access control
contract RoleAware {
Roles public immutable roles;
mapping(uint256 => address) public mainCharacterCache;
mapping(address => mapping(uint256 => bool)) public roleCache;
constructor(address _roles) {
require(_roles != address(0), "Please provide valid roles address");
roles = Roles(_roles);
}
modifier noIntermediary() {
require(
msg.sender == tx.origin,
"Currently no intermediaries allowed for this function call"
);
_;
}
// @dev Throws if called by any account other than the owner or executor
modifier onlyOwnerExec() {
require(
owner() == msg.sender || executor() == msg.sender,
"Roles: caller is not the owner"
);
_;
}
modifier onlyOwnerExecDisabler() {
require(
owner() == msg.sender ||
executor() == msg.sender ||
disabler() == msg.sender,
"Caller is not the owner, executor or authorized disabler"
);
_;
}
modifier onlyOwnerExecActivator() {
require(
owner() == msg.sender ||
executor() == msg.sender ||
isTokenActivator(msg.sender),
"Caller is not the owner, executor or authorized activator"
);
_;
}
function updateRoleCache(uint256 role, address contr) public virtual {
roleCache[contr][role] = roles.getRole(role, contr);
}
function updateMainCharacterCache(uint256 role) public virtual {
mainCharacterCache[role] = roles.mainCharacters(role);
}
function owner() internal view returns (address) {
return roles.owner();
}
function executor() internal returns (address) {
return roles.executor();
}
function disabler() internal view returns (address) {
return mainCharacterCache[DISABLER];
}
function fund() internal view returns (address) {
return mainCharacterCache[FUND];
}
function lending() internal view returns (address) {
return mainCharacterCache[LENDING];
}
function marginRouter() internal view returns (address) {
return mainCharacterCache[MARGIN_ROUTER];
}
function crossMarginTrading() internal view returns (address) {
return mainCharacterCache[CROSS_MARGIN_TRADING];
}
function feeController() internal view returns (address) {
return mainCharacterCache[FEE_CONTROLLER];
}
function price() internal view returns (address) {
return mainCharacterCache[PRICE_CONTROLLER];
}
function admin() internal view returns (address) {
return mainCharacterCache[ADMIN];
}
function incentiveDistributor() internal view returns (address) {
return mainCharacterCache[INCENTIVE_DISTRIBUTION];
}
function tokenAdmin() internal view returns (address) {
return mainCharacterCache[TOKEN_ADMIN];
}
function isBorrower(address contr) internal view returns (bool) {
return roleCache[contr][BORROWER];
}
function isFundTransferer(address contr) internal view returns (bool) {
return roleCache[contr][FUND_TRANSFERER];
}
function isMarginTrader(address contr) internal view returns (bool) {
return roleCache[contr][MARGIN_TRADER];
}
function isFeeSource(address contr) internal view returns (bool) {
return roleCache[contr][FEE_SOURCE];
}
function isMarginCaller(address contr) internal view returns (bool) {
return roleCache[contr][MARGIN_CALLER];
}
function isLiquidator(address contr) internal view returns (bool) {
return roleCache[contr][LIQUIDATOR];
}
function isAuthorizedFundTrader(address contr)
internal
view
returns (bool)
{
return roleCache[contr][AUTHORIZED_FUND_TRADER];
}
function isIncentiveReporter(address contr) internal view returns (bool) {
return roleCache[contr][INCENTIVE_REPORTER];
}
function isTokenActivator(address contr) internal view returns (bool) {
return roleCache[contr][TOKEN_ACTIVATOR];
}
function isStakePenalizer(address contr) internal view returns (bool) {
return roleCache[contr][STAKE_PENALIZER];
}
function isLender(address contr) internal view returns (bool) {
return roleCache[contr][LENDER];
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "../interfaces/IDependencyController.sol";
// we chose not to go with an enum
// to make this list easy to extend
uint256 constant FUND_TRANSFERER = 1;
uint256 constant MARGIN_CALLER = 2;
uint256 constant BORROWER = 3;
uint256 constant MARGIN_TRADER = 4;
uint256 constant FEE_SOURCE = 5;
uint256 constant LIQUIDATOR = 6;
uint256 constant AUTHORIZED_FUND_TRADER = 7;
uint256 constant INCENTIVE_REPORTER = 8;
uint256 constant TOKEN_ACTIVATOR = 9;
uint256 constant STAKE_PENALIZER = 10;
uint256 constant LENDER = 11;
uint256 constant FUND = 101;
uint256 constant LENDING = 102;
uint256 constant MARGIN_ROUTER = 103;
uint256 constant CROSS_MARGIN_TRADING = 104;
uint256 constant FEE_CONTROLLER = 105;
uint256 constant PRICE_CONTROLLER = 106;
uint256 constant ADMIN = 107;
uint256 constant INCENTIVE_DISTRIBUTION = 108;
uint256 constant TOKEN_ADMIN = 109;
uint256 constant DISABLER = 1001;
uint256 constant DEPENDENCY_CONTROLLER = 1002;
/// @title Manage permissions of contracts and ownership of everything
/// owned by a multisig wallet (0xEED9D1c6B4cdEcB3af070D85bfd394E7aF179CBd) during
/// beta and will then be transfered to governance
/// https://github.com/marginswap/governance
contract Roles is Ownable {
mapping(address => mapping(uint256 => bool)) public roles;
mapping(uint256 => address) public mainCharacters;
constructor() Ownable() {
// token activation from the get-go
roles[msg.sender][TOKEN_ACTIVATOR] = true;
}
/// @dev Throws if called by any account other than the owner.
modifier onlyOwnerExecDepController() {
require(
owner() == msg.sender ||
executor() == msg.sender ||
mainCharacters[DEPENDENCY_CONTROLLER] == msg.sender,
"Roles: caller is not the owner"
);
_;
}
function giveRole(uint256 role, address actor)
external
onlyOwnerExecDepController
{
roles[actor][role] = true;
}
function removeRole(uint256 role, address actor)
external
onlyOwnerExecDepController
{
roles[actor][role] = false;
}
function setMainCharacter(uint256 role, address actor)
external
onlyOwnerExecDepController
{
mainCharacters[role] = actor;
}
function getRole(uint256 role, address contr) external view returns (bool) {
return roles[contr][role];
}
/// @dev current executor
function executor() public returns (address exec) {
address depController = mainCharacters[DEPENDENCY_CONTROLLER];
if (depController != address(0)) {
exec = IDependencyController(depController).currentExecutor();
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
interface IDependencyController {
function currentExecutor() external returns (address);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
interface IMarginTrading {
function registerDeposit(
address trader,
address token,
uint256 amount
) external returns (uint256 extinguishAmount);
function registerWithdrawal(
address trader,
address token,
uint256 amount
) external;
function registerBorrow(
address trader,
address token,
uint256 amount
) external;
function registerTradeAndBorrow(
address trader,
address inToken,
address outToken,
uint256 inAmount,
uint256 outAmount
) external returns (uint256 extinguishAmount, uint256 borrowAmount);
function registerOvercollateralizedBorrow(
address trader,
address depositToken,
uint256 depositAmount,
address borrowToken,
uint256 withdrawAmount
) external;
function registerLiquidation(address trader) external;
function getHoldingAmounts(address trader)
external
view
returns (
address[] memory holdingTokens,
uint256[] memory holdingAmounts
);
function getBorrowAmounts(address trader)
external
view
returns (address[] memory borrowTokens, uint256[] memory borrowAmounts);
}
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
library IncentiveReporter {
event AddToClaim(address topic, address indexed claimant, uint256 amount);
event SubtractFromClaim(
address topic,
address indexed claimant,
uint256 amount
);
/// Start / increase amount of claim
function addToClaimAmount(
address topic,
address recipient,
uint256 claimAmount
) internal {
emit AddToClaim(topic, recipient, claimAmount);
}
/// Decrease amount of claim
function subtractFromClaimAmount(
address topic,
address recipient,
uint256 subtractAmount
) internal {
emit SubtractFromClaim(topic, recipient, subtractAmount);
}
}
pragma solidity >=0.5.0;
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
library UniswapStyleLib {
address constant UNISWAP_FACTORY =
0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
address constant SUSHI_FACTORY = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac;
// 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, "Identical address!");
(token0, token1) = tokenA < tokenB
? (tokenA, tokenB)
: (tokenB, tokenA);
require(token0 != address(0), "Zero address!");
}
// fetches and sorts the reserves for a pair
function getReserves(
address pair,
address tokenA,
address tokenB
) internal view returns (uint256 reserveA, uint256 reserveB) {
(address token0, ) = sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 reserve1, ) =
IUniswapV2Pair(pair).getReserves();
(reserveA, reserveB) = tokenA == token0
? (reserve0, reserve1)
: (reserve1, reserve0);
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
require(amountIn > 0, "INSUFFICIENT_INPUT_AMOUNT");
require(
reserveIn > 0 && reserveOut > 0,
"UniswapV2Library: INSUFFICIENT_LIQUIDITY"
);
uint256 amountInWithFee = amountIn * 997;
uint256 numerator = amountInWithFee * reserveOut;
uint256 denominator = reserveIn * 1_000 + 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(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
require(amountOut > 0, "INSUFFICIENT_OUTPUT_AMOUNT");
require(
reserveIn > 0 && reserveOut > 0,
"UniswapV2Library: INSUFFICIENT_LIQUIDITY"
);
uint256 numerator = reserveIn * amountOut * 1_000;
uint256 denominator = (reserveOut - amountOut) * 997;
amountIn = (numerator / denominator) + 1;
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(
uint256 amountIn,
bytes32 amms,
address[] memory tokens
) internal view returns (uint256[] memory amounts, address[] memory pairs) {
require(tokens.length >= 2, "token path too short");
amounts = new uint256[](tokens.length);
amounts[0] = amountIn;
pairs = new address[](tokens.length - 1);
for (uint256 i; i < tokens.length - 1; i++) {
address inToken = tokens[i];
address outToken = tokens[i + 1];
address pair =
amms[i] == 0
? pairForUni(inToken, outToken)
: pairForSushi(inToken, outToken);
pairs[i] = pair;
(uint256 reserveIn, uint256 reserveOut) =
getReserves(pair, inToken, outToken);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(
uint256 amountOut,
bytes32 amms,
address[] memory tokens
) internal view returns (uint256[] memory amounts, address[] memory pairs) {
require(tokens.length >= 2, "token path too short");
amounts = new uint256[](tokens.length);
amounts[amounts.length - 1] = amountOut;
pairs = new address[](tokens.length - 1);
for (uint256 i = tokens.length - 1; i > 0; i--) {
address inToken = tokens[i - 1];
address outToken = tokens[i];
address pair =
amms[i - 1] == 0
? pairForUni(inToken, outToken)
: pairForSushi(inToken, outToken);
pairs[i - 1] = pair;
(uint256 reserveIn, uint256 reserveOut) =
getReserves(pair, inToken, outToken);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
// calculates the CREATE2 address for a pair without making any external calls
function pairForUni(address tokenA, address tokenB)
internal
pure
returns (address pair)
{
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(
uint160(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
UNISWAP_FACTORY,
keccak256(abi.encodePacked(token0, token1)),
hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash
)
)
)
)
);
}
function pairForSushi(address tokenA, address tokenB)
internal
pure
returns (address pair)
{
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(
uint160(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
SUSHI_FACTORY,
keccak256(abi.encodePacked(token0, token1)),
hex"e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303" // init code hash
)
)
)
)
);
}
}
| @dev internal helper swapping exact token for token on AMM | function _fundSwapExactT4T(
uint256[] memory amounts,
uint256 amountOutMin,
address[] memory pairs,
address[] calldata tokens
) internal {
require(
amounts[amounts.length - 1] >= amountOutMin,
"MarginRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
Fund(fund()).withdraw(tokens[0], pairs[0], amounts[0]);
_swap(amounts, pairs, tokens, fund());
}
| 563,896 | [
1,
7236,
4222,
7720,
1382,
5565,
1147,
364,
1147,
603,
432,
8206,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
74,
1074,
12521,
14332,
56,
24,
56,
12,
203,
3639,
2254,
5034,
8526,
3778,
30980,
16,
203,
3639,
2254,
5034,
3844,
1182,
2930,
16,
203,
3639,
1758,
8526,
3778,
5574,
16,
203,
3639,
1758,
8526,
745,
892,
2430,
203,
565,
262,
2713,
288,
203,
3639,
2583,
12,
203,
5411,
30980,
63,
8949,
87,
18,
2469,
300,
404,
65,
1545,
3844,
1182,
2930,
16,
203,
5411,
315,
9524,
8259,
30,
2120,
6639,
42,
1653,
7266,
2222,
67,
15527,
67,
2192,
51,
5321,
6,
203,
3639,
11272,
203,
3639,
478,
1074,
12,
74,
1074,
1435,
2934,
1918,
9446,
12,
7860,
63,
20,
6487,
5574,
63,
20,
6487,
30980,
63,
20,
19226,
203,
3639,
389,
22270,
12,
8949,
87,
16,
5574,
16,
2430,
16,
284,
1074,
10663,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.18;
import "./ERC20Interface.sol";
import "./Ownable.sol";
import "./SafeERC20.sol";
import "./SafeMath.sol";
/**
* TokenVesting
*
* A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Interface;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
ERC20Interface public token;
uint256 public released;
bool public revoked;
/**
* Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
*
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _start when vesting start
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
* @param _token ERC20 token address
*/
function TokenVesting(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable,
address _token
) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
token = ERC20Interface(_token);
}
/**
* Only allow calls from the beneficiary of the vesting contract
*/
modifier onlyBeneficiary() {
require(msg.sender == beneficiary);
_;
}
/**
* Allow the beneficiary to change its address
*
* @param target the address to transfer the right to
*/
function changeBeneficiary(address target) public onlyBeneficiary {
require(target != 0);
beneficiary = target;
}
/**
* Allow beneficiary to release to themselves
*/
function release() public onlyBeneficiary {
require(now >= cliff);
require(!revoked);
_releaseTo(beneficiary);
}
/**
* Transfers vested tokens to a target address.
*
* @param target the address to send the tokens to
*/
function releaseTo(address target) public onlyBeneficiary {
require(now >= cliff);
require(!revoked);
_releaseTo(target);
}
/**
* Allows the owner to revoke the vesting. Tokens already vested are sent to the beneficiary.
*/
function revoke() public onlyOwner {
require(revocable);
require(!revoked);
// Release all vested tokens
_releaseTo(beneficiary);
// Send the remainder to the owner
token.safeTransfer(owner, token.balanceOf(this));
revoked = true;
Revoked();
}
/**
* Calculates the amount that has already vested but hasn't been released yet.
*/
function releasableAmount() public view returns (uint256) {
return vestedAmount().sub(released);
}
/**
* Calculates the amount that has already vested.
*/
function vestedAmount() public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released);
if (now < cliff) {
return 0;
} else if (now >= start.add(duration)) {
return totalBalance;
} else {
return totalBalance.mul(now.sub(start)).div(duration);
}
}
/**
* Transfers vested tokens to beneficiary.
*
* @param target the address to release to
*/
function _releaseTo(address target) internal {
uint256 unreleased = releasableAmount();
require(unreleased > 0);
released = released.add(unreleased);
token.safeTransfer(target, unreleased);
Released(released);
}
}
| * Calculates the amount that has already vested./ | function vestedAmount() public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released);
if (now < cliff) {
return 0;
return totalBalance;
return totalBalance.mul(now.sub(start)).div(duration);
}
}
| 14,058,798 | [
1,
10587,
326,
3844,
716,
711,
1818,
331,
3149,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
331,
3149,
6275,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
783,
13937,
273,
1147,
18,
12296,
951,
12,
2211,
1769,
203,
3639,
2254,
5034,
2078,
13937,
273,
783,
13937,
18,
1289,
12,
9340,
72,
1769,
203,
203,
3639,
309,
261,
3338,
411,
927,
3048,
13,
288,
203,
5411,
327,
374,
31,
203,
5411,
327,
2078,
13937,
31,
203,
5411,
327,
2078,
13937,
18,
16411,
12,
3338,
18,
1717,
12,
1937,
13,
2934,
2892,
12,
8760,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
/**
* @title A vesting contract for ERC-20 tokens with a voting extension
* @author Todd Chapman
* @notice Use this contract with OpenZepplin ERC-20 contracts that are used for voting
* @dev Minimalist implementation of a ERC-20 token vesting contract
*
* The base implementation was taken from Uniswap's governance repository:
* https://github.com/Uniswap/governance/blob/master/contracts/TreasuryVester.sol
*
* This vesting contract allows the deployer to set a recipient, a vesting amount,
* a cliff, and vesting end date. Tokens linearly vest from the cliff date to the end
* date.
*
* Since Hypertoken is a voting token, and thus has an extension function for delegating
* voting power to an address other than the holder of the Hypertoken balance, this vesting
* contract allows the beneficiary to claim their voting rights while the vesting contract
* is in custody of their token through a call to `delegate`.
*
* For more info on ERC-20 voting extension see:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/ERC20Votes.sol
*
* See unit tests for example usage:
* https://github.com/GoHypernet/hypernet-protocol/blob/dev/packages/contracts/test/vesting-test.js
*/
contract Vester {
using SafeMath for uint;
/// @dev address of token to be vested
address public h;
/// @dev address of the beneficiary of the vesting contract
address public recipient;
/// @dev amount of h to be vested
uint public vestingAmount;
/// @dev timestamp when vesting begins; use timeNow to help set an appropriate time
uint public vestingBegin;
/// @dev timestamp when first token becomes available to the beneficiary; use timeNow to help set an appropriate time
uint public vestingCliff;
/// @dev timestamp when entirety of vestingAmount is available to the beneficiary; use timeNow to help set an appropriate time
uint public vestingEnd;
/// @dev last timestamp that claim was successfully called
uint public lastUpdate;
/// @dev Constructor definition
/// @param h_ address of the ERC-20 token implementing Hypernetoken
/// @param recipient_ address of the beneficiary account
/// @param vestingAmount_ total amount of h_ due to recipient_
/// @param vestingBegin_ timestamp to use for the starting point of vesting period
/// @param vestingCliff_ timestamp when recipient can redeem first allocation of token
/// @param vestingEnd_ timestamp when all tokens are available to the beneficiary
constructor(
address h_,
address recipient_,
uint vestingAmount_,
uint vestingBegin_,
uint vestingCliff_,
uint vestingEnd_
) {
require(vestingBegin_ >= block.timestamp, 'Vester::constructor: vesting begin too early');
require(vestingCliff_ >= vestingBegin_, 'Vester::constructor: cliff is too early');
require(vestingEnd_ > vestingCliff_, 'Vester::constructor: end is too early');
h = h_;
recipient = recipient_;
vestingAmount = vestingAmount_;
vestingBegin = vestingBegin_;
vestingCliff = vestingCliff_;
vestingEnd = vestingEnd_;
lastUpdate = vestingBegin;
}
/// @notice helper function that returns the current timestamp
/// @dev This function can help get your timestamp format right in testing
/// @return timenow returns the current block timestamp
function timeNow() public view returns (uint timenow) {
timenow = block.timestamp;
}
/// @notice allows the beneficiary to change the beneficiary address to a new address
/// @dev This function can only be called by the account set in the recipient variable
/// @param recipient_ address to set as the new beneficiary
function setRecipient(address recipient_) public {
require(msg.sender == recipient, 'Vester::setRecipient: unauthorized');
recipient = recipient_;
}
/// @notice delegate delegates votes associated with tokens held by this contract to an address specified by the beneficiary
/// @dev The function allows for beneficiaries to have voting rights before they take possession of their tokens
/// @param delegate_ address to recieve the voting rights, does not necessarly have to be the beneficiary
function delegate(address delegate_) public {
require(msg.sender == recipient, 'Vester::setRecipient: unauthorized');
IHypertoken(h).delegate(delegate_);
}
/// @notice Call this function to disperse holdings to the beneficiary account
/// @dev This function can be called by any account to save gas for the recipient, but vested token is only sent to the address stored in recipient
function claim() public {
require(block.timestamp >= vestingCliff, 'Vester::claim: not time yet');
uint amount;
if (block.timestamp >= vestingEnd) {
amount = IHypertoken(h).balanceOf(address(this));
} else {
amount = vestingAmount.mul(block.timestamp - lastUpdate).div(vestingEnd - vestingBegin);
lastUpdate = block.timestamp;
}
require(IHypertoken(h).transfer(recipient, amount), "Vester::claim: token transfer failed");
}
}
/// @dev a minimal interface for ERC-20 token with external delegate function call
interface IHypertoken {
function balanceOf(address account) external view returns (uint);
function transfer(address dst, uint rawAmount) external returns (bool);
function delegate(address delegatee) external;
} | @dev a minimal interface for ERC-20 token with external delegate function call | interface IHypertoken {
function balanceOf(address account) external view returns (uint);
function transfer(address dst, uint rawAmount) external returns (bool);
function delegate(address delegatee) external;
} | 924,175 | [
1,
69,
16745,
1560,
364,
4232,
39,
17,
3462,
1147,
598,
3903,
7152,
445,
745,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5831,
467,
17507,
672,
969,
288,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
3903,
1476,
1135,
261,
11890,
1769,
203,
565,
445,
7412,
12,
2867,
3046,
16,
2254,
1831,
6275,
13,
3903,
1135,
261,
6430,
1769,
203,
565,
445,
7152,
12,
2867,
7152,
73,
13,
3903,
31,
225,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "../proxyLib/OwnableUpgradeable.sol";
import "../interfaces/token/IWETH.sol";
import "../interfaces/token/ILPERC20.sol";
import "../interfaces/uniswap/IUniswapV2.sol";
import "../interfaces/uniswap/IUniswapFactory.sol";
import "hardhat/console.sol";
/// @title Plexus LP Wrapper Contract
/// @author Team Plexus
contract WrapAndUnWrap is OwnableUpgradeable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Contract state variables
address public WETH_TOKEN_ADDRESS; // Contract address for WETH tokens
bool public changeRecpientIsOwner;
address private uniAddress;
address private uniFactoryAddress;
uint256 public fee;
uint256 public maxfee;
IUniswapV2 private uniswapExchange;
IUniswapFactory private factory;
event WrapV2(address lpTokenPairAddress, uint256 amount);
event UnWrapV2(uint256 amount);
event RemixUnwrap(uint256 amount);
event RemixWrap(address lpTokenPairAddress, uint256 amount);
constructor() payable {
}
/**
* @notice Executed on a call to the contract if none of the other
* functions match the given function signature, or if no data was
* supplied at all and there is no receive Ether function
*/
fallback() external payable {
}
/**
* @notice Function executed on plain ether transfers and on a call to the
* contract with empty calldata
*/
receive() external payable {
}
/**
* @notice Initialize the Wrapper contract
* @param _weth Address to the WETH token contract
* @param _uniAddress Address to the Uniswap V2 router contract
* @param _uniFactoryAddress Address to the Uniswap factory contract
*/
function initialize(
address _weth,
address _uniAddress,
address _uniFactoryAddress
)
public
initializeOnceOnly
{
WETH_TOKEN_ADDRESS = _weth;
uniAddress = _uniAddress;
uniswapExchange = IUniswapV2(uniAddress);
uniFactoryAddress = _uniFactoryAddress;
factory = IUniswapFactory(uniFactoryAddress);
fee = 0;
maxfee = 0;
changeRecpientIsOwner = false;
}
/**
* @notice Allow owner to collect a small fee from trade imbalances on
* LP conversions
* @param changeRecpientIsOwnerBool If set to true, allows owner to collect
* fees from pair imbalances
*/
function updateChangeRecipientBool(
bool changeRecpientIsOwnerBool
)
external
onlyOwner
returns (bool)
{
changeRecpientIsOwner = changeRecpientIsOwnerBool;
return true;
}
/**
* @notice Update the Uniswap exchange contract address
* @param newAddress Uniswap exchange contract address to be updated
*/
function updateUniswapExchange(address newAddress) external onlyOwner returns (bool) {
uniswapExchange = IUniswapV2(newAddress);
uniAddress = newAddress;
return true;
}
/**
* @notice Update the Uniswap factory contract address
* @param newAddress Uniswap factory contract address to be updated
*/
function updateUniswapFactory(address newAddress) external onlyOwner returns (bool) {
factory = IUniswapFactory(newAddress);
uniFactoryAddress = newAddress;
return true;
}
/**
* @notice Allow admins to withdraw accidentally deposited tokens
* @param token Address to the token to be withdrawn
* @param amount Amount of specified token to be withdrawn
* @param destination Address where the withdrawn tokens should be
* transferred
*/
function adminEmergencyWithdrawTokens(
address token,
uint256 amount,
address payable destination
)
public
onlyOwner
returns (bool)
{
if (address(token) == address(0x0)) {
destination.transfer(amount);
} else {
IERC20 token_ = IERC20(token);
token_.safeTransfer(destination, amount);
}
return true;
}
/**
* @notice Update the protocol fee rate
* @param newFee Updated fee rate to be charged
*/
function setFee(uint256 newFee) public onlyOwner returns (bool) {
require(
newFee <= maxfee,
"Admin cannot set the fee higher than the current maxfee"
);
fee = newFee;
return true;
}
/**
* @notice Set the max protocol fee rate
* @param newMax Updated maximum fee rate value
*/
function setMaxFee(uint256 newMax) public onlyOwner returns (bool) {
require(maxfee == 0, "Admin can only set max fee once and it is perm");
maxfee = newMax;
return true;
}
function swap(
address sourceToken,
address destinationToken,
address[] memory path,
uint256 amount,
uint256 userSlippageTolerance,
uint256 deadline
) private returns (uint256) {
if (sourceToken != address(0x0)) {
IERC20(sourceToken).safeTransferFrom(msg.sender, address(this), amount);
}
conductUniswap(sourceToken, destinationToken, path, amount, userSlippageTolerance, deadline);
uint256 thisBalance = IERC20(destinationToken).balanceOf(address(this));
IERC20(destinationToken).safeTransfer(msg.sender, thisBalance);
return thisBalance;
}
function createWrap(
address sourceToken,
address[] memory destinationTokens,
address[][] memory paths,
uint256 amount,
uint256 userSlippageTolerance,
uint256 deadline,
bool remixing
) private returns (address, uint256) {
if (sourceToken == address(0x0)) {
IWETH(WETH_TOKEN_ADDRESS).deposit{value: msg.value}();
amount = msg.value;
} else {
if(!remixing) { // only transfer when not remixing
IERC20(sourceToken).safeTransferFrom(msg.sender, address(this), amount);
}
}
if (destinationTokens[0] == address(0x0)) {
destinationTokens[0] = WETH_TOKEN_ADDRESS;
}
if (destinationTokens[1] == address(0x0)) {
destinationTokens[1] = WETH_TOKEN_ADDRESS;
}
if (sourceToken != destinationTokens[0]) {
conductUniswap(
sourceToken,
destinationTokens[0],
paths[0],
amount.div(2),
userSlippageTolerance,
deadline
);
}
if (sourceToken != destinationTokens[1]) {
conductUniswap(
sourceToken,
destinationTokens[1],
paths[1],
amount.div(2),
userSlippageTolerance,
deadline
);
}
IERC20 dToken1 = IERC20(destinationTokens[0]);
IERC20 dToken2 = IERC20(destinationTokens[1]);
uint256 dTokenBalance1 = dToken1.balanceOf(address(this));
uint256 dTokenBalance2 = dToken2.balanceOf(address(this));
if (dToken1.allowance(address(this), uniAddress) < dTokenBalance1.mul(2)) {
dToken1.safeIncreaseAllowance(uniAddress, dTokenBalance1.mul(3));
}
if (dToken2.allowance(address(this), uniAddress) < dTokenBalance2.mul(2)) {
dToken2.safeIncreaseAllowance(uniAddress, dTokenBalance2.mul(3));
}
uniswapExchange.addLiquidity(
destinationTokens[0],
destinationTokens[1],
dTokenBalance1,
dTokenBalance2,
1,
1,
address(this),
1000000000000000000000000000
);
address thisPairAddress =
factory.getPair(destinationTokens[0], destinationTokens[1]);
IERC20 lpToken = IERC20(thisPairAddress);
uint256 thisBalance = lpToken.balanceOf(address(this));
if (fee > 0) {
uint256 totalFee = (thisBalance.mul(fee)).div(10000);
if (totalFee > 0) {
lpToken.safeTransfer(owner(), totalFee);
}
thisBalance = lpToken.balanceOf(address(this));
lpToken.safeTransfer(msg.sender, thisBalance);
} else {
lpToken.safeTransfer(msg.sender, thisBalance);
}
// Transfer any change to changeRecipient
// (from a pair imbalance. Should never be more than a few basis points)
address changeRecipient = msg.sender;
if (changeRecpientIsOwner == true) {
changeRecipient = owner();
}
if (dToken1.balanceOf(address(this)) > 0) {
dToken1.safeTransfer(changeRecipient, dToken1.balanceOf(address(this)));
}
if (dToken2.balanceOf(address(this)) > 0) {
dToken2.safeTransfer(changeRecipient, dToken2.balanceOf(address(this)));
}
return (thisPairAddress, thisBalance);
}
/**
* @notice Wrap a source token based on the specified
* destination token(s)
* @param sourceToken Address to the source token contract
* @param destinationTokens Array describing the token(s) which the source
* @param paths Paths for uniswap
* token will be wrapped into
* @param amount Amount of source token to be wrapped
* @param userSlippageTolerance Maximum permissible user slippage tolerance
* @return Address to the token contract for the destination token and the
* amount of wrapped tokens
*/
function wrap(
address sourceToken,
address[] memory destinationTokens,
address[][] memory paths,
uint256 amount,
uint256 userSlippageTolerance,
uint256 deadline
)
public
payable
returns (address, uint256)
{
if (destinationTokens.length == 1) {
uint256 swapAmount = swap(sourceToken, destinationTokens[0], paths[0], amount, userSlippageTolerance, deadline);
return (destinationTokens[0], swapAmount);
} else {
bool remixing = false;
(address lpTokenPairAddress, uint256 lpTokenAmount) = createWrap(sourceToken, destinationTokens, paths, amount, userSlippageTolerance, deadline, remixing);
emit WrapV2(lpTokenPairAddress, lpTokenAmount);
return (lpTokenPairAddress, lpTokenAmount);
}
}
function removeWrap(
address sourceToken,
address destinationToken,
address[][] memory paths,
uint256 amount,
uint256 userSlippageTolerance,
uint256 deadline,
bool remixing
)
private
returns (uint256)
{
address originalDestinationToken = destinationToken;
IERC20 sToken = IERC20(sourceToken);
if (destinationToken == address(0x0)) {
destinationToken = WETH_TOKEN_ADDRESS;
}
if (sourceToken != address(0x0)) {
sToken.safeTransferFrom(msg.sender, address(this), amount);
}
ILPERC20 thisLpInfo = ILPERC20(sourceToken);
address token0 = thisLpInfo.token0();
address token1 = thisLpInfo.token1();
if (sToken.allowance(address(this), uniAddress) < amount.mul(2)) {
sToken.safeIncreaseAllowance(uniAddress, amount.mul(3));
}
uniswapExchange.removeLiquidity(
token0,
token1,
amount,
0,
0,
address(this),
1000000000000000000000000000
);
uint256 pTokenBalance = IERC20(token0).balanceOf(address(this));
uint256 pTokenBalance2 = IERC20(token1).balanceOf(address(this));
if (token0 != destinationToken) {
conductUniswap(
token0,
destinationToken,
paths[0],
pTokenBalance,
userSlippageTolerance,
deadline
);
}
if (token1 != destinationToken) {
conductUniswap(
token1,
destinationToken,
paths[1],
pTokenBalance2,
userSlippageTolerance,
deadline
);
}
IERC20 dToken = IERC20(destinationToken);
uint256 destinationTokenBalance = dToken.balanceOf(address(this));
if (remixing) {
emit RemixUnwrap(destinationTokenBalance);
}
else { // we only transfer the tokens to the user when not remixing
if (originalDestinationToken == address(0x0)) {
IWETH(WETH_TOKEN_ADDRESS).withdraw(destinationTokenBalance);
if (fee > 0) {
uint256 totalFee = (address(this).balance.mul(fee)).div(10000);
if (totalFee > 0) {
payable(owner()).transfer(totalFee);
}
payable(msg.sender).transfer(address(this).balance);
} else {
payable(msg.sender).transfer(address(this).balance);
}
} else {
if (fee > 0) {
uint256 totalFee = (destinationTokenBalance.mul(fee)).div(10000);
if (totalFee > 0) {
dToken.safeTransfer(owner(), totalFee);
}
destinationTokenBalance = dToken.balanceOf(address(this));
dToken.safeTransfer(msg.sender, destinationTokenBalance);
} else {
dToken.safeTransfer(msg.sender, destinationTokenBalance);
}
}
}
return destinationTokenBalance;
}
/**
* @notice Unwrap a source token based to the specified destination token
* @param sourceToken Address to the source token contract
* @param destinationToken Address to the destination token contract
* @param paths Paths for uniswap
* @param lpTokenPairAddress address for lp token
* @param amount Amount of source token to be unwrapped
* @param userSlippageTolerance Maximum permissible user slippage tolerance
* @return Amount of the destination token returned from unwrapping the
* source token
*/
function unwrap(
address sourceToken,
address destinationToken,
address lpTokenPairAddress,
address[][] calldata paths,
uint256 amount,
uint256 userSlippageTolerance,
uint256 deadline
)
public
payable
returns (uint256)
{
if (lpTokenPairAddress == address(0x0)) {
return swap(sourceToken, destinationToken, paths[0], amount, userSlippageTolerance, deadline);
} else {
bool remixing = false; //flag indicates whether we're remixing or not
uint256 destAmount = removeWrap(lpTokenPairAddress, destinationToken, paths, amount, userSlippageTolerance, deadline, remixing);
emit UnWrapV2(destAmount);
return destAmount;
}
}
/**
* @notice Unwrap a source token and wrap it into a different destination token
* @param lpTokenPairAddress Address for the LP pair to remix
* @param unwrapOutputToken Address for the initial output token of remix
* @param destinationTokens Address to the destination tokens to be remixed to
* @param unwrapPaths Paths best uniswap trade paths for doing the unwrapping
* @param wrapPaths Paths best uniswap trade paths for doing the wrapping to the new LP token
* @param amount Amount of LP Token to be remixed
* @param userSlippageTolerance Maximum permissible user slippage tolerance
* @return Amount of the destination token returned from unwrapping the
* source LP token
*/
function remix(
address lpTokenPairAddress,
address unwrapOutputToken,
address[] memory destinationTokens,
address[][] memory unwrapPaths,
address[][] memory wrapPaths,
uint256 amount,
uint256 userSlippageTolerance,
uint256 deadline
)
public
payable
returns (uint256)
{
bool remixing = true; //flag indicates whether we're remixing or not
uint256 destAmount = removeWrap(lpTokenPairAddress, unwrapOutputToken, unwrapPaths, amount, userSlippageTolerance, deadline, remixing);
IERC20 dToken = IERC20(unwrapOutputToken);
uint256 destinationTokenBalance = dToken.balanceOf(address(this));
require(destAmount == destinationTokenBalance, "Error: Remix output token balance not correct");
// then now we create the new LP token
address outputToken = unwrapOutputToken;
address [] memory dTokens = destinationTokens;
address [][] memory paths = wrapPaths;
uint256 slippageTolerance = userSlippageTolerance;
uint256 timeout = deadline;
bool remixingToken = true; //flag indicates whether we're remixing or not
(address remixedLpTokenPairAddress, uint256 lpTokenAmount) = createWrap(outputToken, dTokens, paths, destinationTokenBalance, slippageTolerance, timeout, remixingToken);
emit RemixWrap(remixedLpTokenPairAddress, lpTokenAmount);
return lpTokenAmount;
}
/**
* @notice Given an input asset amount and an array of token addresses,
* calculates all subsequent maximum output token amounts for each pair of
* token addresses in the path.
* @param theAddresses Array of addresses that form the Routing swap path
* @param amount Amount of input asset token
* @return amounts1 Array with maximum output token amounts for all token
* pairs in the swap path
*/
function getPriceFromUniswap(address[] memory theAddresses, uint256 amount)
public
view
returns (uint256[] memory amounts1) {
try uniswapExchange.getAmountsOut(
amount,
theAddresses
) returns (uint256[] memory amounts) {
return amounts;
} catch {
uint256[] memory amounts2 = new uint256[](2);
amounts2[0] = 0;
amounts2[1] = 0;
return amounts2;
}
}
/**
* @notice Retrieve the LP token address for a given pair of tokens
* @param token1 Address to the first token in the LP pair
* @param token2 Address to the second token in the LP pair
* @return lpAddr Address to the LP token contract composed of the given
* token pair
*/
function getLPTokenByPair(
address token1,
address token2
)
public
view
returns (address lpAddr)
{
address thisPairAddress = factory.getPair(token1, token2);
return thisPairAddress;
}
/**
* @notice Retrieve the balance of a given token for a specified user
* @param userAddress Address to the user's wallet
* @param tokenAddress Address to the token for which the balance is to be
* retrieved
* @return Balance of the given token in the specified user wallet
*/
function getUserTokenBalance(
address userAddress,
address tokenAddress
)
public
view
returns (uint256)
{
IERC20 token = IERC20(tokenAddress);
return token.balanceOf(userAddress);
}
/**
* @notice Retrieve minimum output amount required based on uniswap routing
* path and maximum permissible slippage
* @param paths Array list describing the Uniswap router swap path
* @param amount Amount of input tokens to be swapped
* @param userSlippageTolerance Maximum permissible user slippage tolerance
* @return Minimum amount of output tokens the input token can be swapped
* for, based on the Uniswap prices and Slippage tolerance thresholds
*/
function getAmountOutMin(
address[] memory paths,
uint256 amount,
uint256 userSlippageTolerance
)
public
view
returns (uint256)
{
uint256[] memory assetAmounts = getPriceFromUniswap(paths, amount);
// this is the index of the output token we're swapping to based on the paths
uint outputTokenIndex = assetAmounts.length - 1;
require(userSlippageTolerance <= 100, "userSlippageTolerance can not be larger than 100");
return SafeMath.div(SafeMath.mul(assetAmounts[outputTokenIndex], (100 - userSlippageTolerance)), 100);
}
/**
* @notice Perform a Uniswap transaction to swap between a given pair of
* tokens of the specified amount
* @param sellToken Address to the token being sold as part of the swap
* @param buyToken Address to the token being bought as part of the swap
* @param path Path for uniswap
* @param amount Transaction amount denoted in terms of the token sold
* @param userSlippageTolerance Maximum permissible slippage limit
* @return amounts1 Tokens received once the swap is completed
*/
function conductUniswap(
address sellToken,
address buyToken,
address[] memory path,
uint256 amount,
uint256 userSlippageTolerance,
uint256 deadline
)
internal
returns (uint256 amounts1)
{
if (sellToken == address(0x0) && buyToken == WETH_TOKEN_ADDRESS) {
IWETH(buyToken).deposit{value: msg.value}();
return amount;
}
if (sellToken == address(0x0)) {
// addresses[0] = WETH_TOKEN_ADDRESS;
// addresses[1] = buyToken;
uint256 amountOutMin = getAmountOutMin(path, amount, userSlippageTolerance);
uniswapExchange.swapExactETHForTokens{value: msg.value}(
amountOutMin,
path,
address(this),
deadline
);
} else {
IERC20 sToken = IERC20(sellToken);
if (sToken.allowance(address(this), uniAddress) < amount.mul(2)) {
sToken.safeIncreaseAllowance(uniAddress, amount.mul(3));
}
uint256[] memory amounts = conductUniswapT4T(
path,
amount,
userSlippageTolerance,
deadline
);
uint256 resultingTokens = amounts[amounts.length - 1];
return resultingTokens;
}
}
/**
* @notice Using Uniswap, exchange an exact amount of input tokens for as
* many output tokens as possible, along the route determined by the path.
* @param paths Array of addresses representing the path where the
* first address is the input token and the last address is the output
* token
* @param amount Amount of input tokens to be swapped
* @param userSlippageTolerance Maximum permissible slippage tolerance
* @return amounts_ The input token amount and all subsequent output token
* amounts
*/
function conductUniswapT4T(
address[] memory paths,
uint256 amount,
uint256 userSlippageTolerance,
uint256 deadline
)
internal
returns (uint256[] memory amounts_)
{
uint256 amountOutMin = getAmountOutMin(paths, amount, userSlippageTolerance);
uint256[] memory amounts =
uniswapExchange.swapExactTokensForTokens(
amount,
amountOutMin,
paths,
address(this),
deadline
);
return amounts;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
// 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) {
unchecked {
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) {
unchecked {
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) {
return a + b;
}
/**
* @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 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) {
return a * b;
}
/**
* @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.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
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) {
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) {
unchecked {
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.
*
* 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) {
unchecked {
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) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
pragma experimental ABIEncoderV2;
import './OwnableProxied.sol';
contract OwnableUpgradeable is OwnableProxied {
/*
* @notice Modifier to make body of function only execute if the contract has not already been initialized.
*/
address payable public proxy;
modifier initializeOnceOnly() {
if(!initialized[target]) {
initialized[target] = true;
emit EventInitialized(target);
_;
} else revert();
}
modifier onlyProxy() {
require(msg.sender == proxy);
_;
}
/**
* @notice Will always fail if called. This is used as a placeholder for the contract ABI.
* @dev This is code is never executed by the Proxy using delegate call
*/
function upgradeTo(address) public pure override {
assert(false);
}
/**
* @notice Initialize any state variables that would normally be set in the contructor.
* @dev Initialization functionality MUST be implemented in inherited upgradeable contract if the child contract requires
* variable initialization on creation. This is because the contructor of the child contract will not execute
* and set any state when the Proxy contract targets it.
* This function MUST be called stright after the Upgradeable contract is set as the target of the Proxy. This method
* can be overwridden so that it may have arguments. Make sure that the initializeOnceOnly() modifier is used to protect
* from being initialized more than once.
* If a contract is upgraded twice, pay special attention that the state variables are not initialized again
*/
/*function initialize() public initializeOnceOnly {
// initialize contract state variables here
}*/
function setProxy(address payable theAddress) public onlyOwner {
proxy = theAddress;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
interface ILPERC20 {
function token0() external view returns (address);
function token1() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
interface IUniswapV2 {
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 returns (uint256 amountToken, uint256 amountETH, uint256 liquidity);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function getAmountsOut(
uint256 amountIn,
address[] calldata path
) external view returns (uint256[] memory amounts);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
interface IUniswapFactory {
function getPair(address tokenA, address tokenB)
external
view
returns (address pair);
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
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);
}
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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
pragma experimental ABIEncoderV2;
import "./Ownable.sol";
/*
* @title Proxied v0.5
* @author Jack Tanner
* @notice The Proxied contract acts as the parent contract to Proxy and Upgradeable with and creates space for
* state variables, functions and events that will be used in the upgraeable system.
*
* @dev Both the Proxy and Upgradeable need to hae the target and initialized state variables stored in the exact
* same storage location, which is why they must both inherit from Proxied. Defining them in the saparate contracts
* does not work.
*
* @param target - This stores the current address of the target Upgradeable contract, which can be modified by
* calling upgradeTo()
*
* @param initialized - This mapping records which targets have been initialized with the Upgradeable.initialize()
* function. Target Upgradeable contracts can only be intitialed once.
*/
abstract contract OwnableProxied is Ownable {
address public target;
mapping(address => bool) public initialized;
event EventUpgrade(
address indexed newTarget,
address indexed oldTarget,
address indexed admin
);
event EventInitialized(address indexed target);
function upgradeTo(address _target) public virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
import "@openzeppelin/contracts/utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
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");
_;
}
function changeOwner(address newOwner) public onlyOwner returns (bool) {
_owner = newOwner;
return true;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.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;
}
}
| * @notice Wrap a source token based on the specified destination token(s) @param sourceToken Address to the source token contract @param destinationTokens Array describing the token(s) which the source @param paths Paths for uniswap token will be wrapped into @param amount Amount of source token to be wrapped @param userSlippageTolerance Maximum permissible user slippage tolerance @return Address to the token contract for the destination token and the amount of wrapped tokens/ | {
function wrap(
address sourceToken,
address[] memory destinationTokens,
address[][] memory paths,
uint256 amount,
uint256 userSlippageTolerance,
uint256 deadline
)
public
payable
returns (address, uint256)
if (destinationTokens.length == 1) {
uint256 swapAmount = swap(sourceToken, destinationTokens[0], paths[0], amount, userSlippageTolerance, deadline);
return (destinationTokens[0], swapAmount);
bool remixing = false;
(address lpTokenPairAddress, uint256 lpTokenAmount) = createWrap(sourceToken, destinationTokens, paths, amount, userSlippageTolerance, deadline, remixing);
emit WrapV2(lpTokenPairAddress, lpTokenAmount);
return (lpTokenPairAddress, lpTokenAmount);
}
} else {
}
| 10,210,250 | [
1,
2964,
279,
1084,
1147,
2511,
603,
326,
1269,
2929,
1147,
12,
87,
13,
225,
1084,
1345,
5267,
358,
326,
1084,
1147,
6835,
225,
2929,
5157,
1510,
16868,
326,
1147,
12,
87,
13,
1492,
326,
1084,
225,
2953,
16643,
364,
640,
291,
91,
438,
1147,
903,
506,
5805,
1368,
225,
3844,
16811,
434,
1084,
1147,
358,
506,
5805,
225,
729,
55,
3169,
2433,
22678,
18848,
293,
1840,
1523,
729,
272,
3169,
2433,
10673,
327,
5267,
358,
326,
1147,
6835,
364,
326,
2929,
1147,
471,
326,
3844,
434,
5805,
2430,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
288,
203,
565,
445,
2193,
12,
203,
3639,
1758,
1084,
1345,
16,
203,
3639,
1758,
8526,
3778,
2929,
5157,
16,
203,
3639,
1758,
63,
6362,
65,
3778,
2953,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
2254,
5034,
729,
55,
3169,
2433,
22678,
16,
203,
3639,
2254,
5034,
14096,
203,
565,
262,
203,
3639,
1071,
203,
3639,
8843,
429,
203,
3639,
1135,
261,
2867,
16,
2254,
5034,
13,
203,
3639,
309,
261,
10590,
5157,
18,
2469,
422,
404,
13,
288,
203,
5411,
2254,
5034,
7720,
6275,
273,
7720,
12,
3168,
1345,
16,
2929,
5157,
63,
20,
6487,
2953,
63,
20,
6487,
3844,
16,
729,
55,
3169,
2433,
22678,
16,
14096,
1769,
203,
5411,
327,
261,
10590,
5157,
63,
20,
6487,
7720,
6275,
1769,
203,
5411,
1426,
849,
697,
310,
273,
629,
31,
203,
5411,
261,
2867,
12423,
1345,
4154,
1887,
16,
2254,
5034,
12423,
1345,
6275,
13,
273,
752,
2964,
12,
3168,
1345,
16,
2929,
5157,
16,
2953,
16,
3844,
16,
729,
55,
3169,
2433,
22678,
16,
14096,
16,
849,
697,
310,
1769,
203,
5411,
3626,
4266,
58,
22,
12,
9953,
1345,
4154,
1887,
16,
12423,
1345,
6275,
1769,
203,
5411,
327,
261,
9953,
1345,
4154,
1887,
16,
12423,
1345,
6275,
1769,
203,
3639,
289,
203,
3639,
289,
469,
288,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract BorrowToken is
ERC721URIStorage,
ERC721Enumerable,
Ownable,
ERC721Burnable
{
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
string public prefix = "http://app.kyoko.finance/btoken/";
string public suffix = ".png";
constructor() ERC721("KyokoBToken", "KB") {}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, amount);
}
function mint(address player) public onlyOwner returns (uint256) {
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
string memory _index = uint2str(newItemId);
string memory _URI = strConcat(prefix, _index, suffix);
_mint(player, newItemId);
_setTokenURI(newItemId, _URI);
return newItemId;
}
function burn(uint256 tokenId) public virtual override(ERC721Burnable) {
super._burn(tokenId);
}
function _burn(uint256 tokenId)
internal
virtual
override(ERC721, ERC721URIStorage)
{
super._burn(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function tokenURI(uint256 tokenId)
public
view
virtual
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function uint2str(uint256 _i)
public
pure
returns (string memory _uintAsString)
{
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;
while (_i != 0) {
k = k - 1;
uint8 temp = (48 + uint8(_i - (_i / 10) * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
function strConcat(
string memory _a,
string memory _b,
string memory _c
) public pure returns (string memory) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
string memory ret = new string(_ba.length + _bb.length + _bc.length);
bytes memory bret = bytes(ret);
uint256 k = 0;
for (uint256 i = 0; i < _ba.length; i++) bret[k++] = _ba[i];
for (uint256 i = 0; i < _bb.length; i++) bret[k++] = _bb[i];
for (uint256 i = 0; i < _bc.length; i++) bret[k++] = _bc[i];
return string(ret);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "./BorrowToken.sol";
import "./LenderToken.sol";
contract Kyoko is Ownable, ERC721Holder {
using SafeMath for uint256;
using SafeERC20 for IERC20;
BorrowToken public bToken; // bToken
LenderToken public lToken; // lToken
// If true, any operation will be rejected
bool public pause = false;
// fixed interestRate: 12%, perBlock 15s, month 30 days, year 12 months, preBlock interestRate = 0.12 * 10**18 / (Seconds * Minutes * Hours * Days * Months / perBlockTime(15s) )
uint256 public interestRate = 57870370371;
uint256 public cycle = 90 days; // Minimum borrowing cycle
uint256 public emergencyCycle = 30 days; // Minimum emergency cycle
uint256 public fee = 50; // admin fee
IERC20[] public whiteList; // whiteList
struct MARK {
bool isBorrow; // has borrow erc20
bool isRepay; // has repay erc20
bool hasWithdraw; // This nft has withdraw
}
struct Nft {
address holder; // nft holder
uint256 tokenId; // nft tokenId
IERC721 nftToken; // nft address
uint256 amount; // debt amount
IERC20 erc20Token; // debt token address
uint256 bTokenId; // btoken id
uint256 lTokenId; // ltoken id
uint256 borrowBlock; // borrow block number
uint256 borrowTimestamp; // borrow timestamp
uint256 emergencyTimestamp; // emergency timestamp
uint256 repayAmount; // repayAmount
MARK marks;
}
IERC721[] public NftAdrList;
mapping(IERC721 => Nft[]) public NftMap; // Collaterals mapping
// received collateral
event NFTReceived(
address operator,
address from,
uint256 tokenId,
bytes data
);
// deposit collateral
event DepositErc721(
uint256 _tokenId,
IERC721 _nftToken,
uint256 _amount,
IERC20 _erc20Token
);
// lend erc20
event LendERC20(
uint256 _tokenId,
IERC721 _nftToken,
uint256 _amount,
IERC20 _erc20Token,
uint256 _bTokenId
);
// borrow erc20
event Borrow(
uint256 _tokenId,
IERC721 _nftToken,
uint256 _amount,
IERC20 _erc20Token,
uint256 _bTokenId
);
// repay erc20
event Repay(
uint256 _tokenId,
IERC721 _nftToken,
uint256 _amount,
IERC20 _erc20Token,
uint256 _bTokenId
);
// Claim collateral
event ClaimCollateral(
uint256 _tokenId,
IERC721 _nftToken,
IERC20 _erc20Token,
uint256 _bTokenId
);
// LToken claim erc20 token
event LTokenClaimERC20(
uint256 _tokenId,
IERC721 _nftToken,
uint256 _amount,
IERC20 _erc20Token,
uint256 _lenderNftTokenId,
uint256 _bTokenId
);
// execute emergency to warning holder
event ExecuteEmergency(
uint256 _tokenId,
IERC721 _nftToken,
IERC20 _erc20Token,
uint256 _lenderNftTokenId,
uint256 _bTokenId
);
// Liquidate collateral
event Liquidate(
uint256 _tokenId,
IERC721 _nftToken,
IERC20 _erc20Token,
uint256 _lenderNftTokenId,
uint256 _bTokenId
);
constructor(BorrowToken _bToken, LenderToken _lToken) {
bToken = _bToken;
lToken = _lToken;
}
modifier isPause() {
require(!pause, "Now Pause");
_;
}
modifier checkDebt(uint256 _amount) {
require(_amount > 0, "The amount must > 0");
_;
}
modifier checkWhiteList(IERC20 _address) {
bool include;
for (uint256 index = 0; index < whiteList.length; index++) {
if (whiteList[index] == _address) {
include = true;
break;
}
}
require(include, "The address is not whitelisted");
_;
}
modifier checkCollateralStatus(
uint256 _nftTokenId,
IERC721 _nftToken,
uint256 _bTokenId,
IERC20 _erc20Token
) {
Nft memory _nft =
_findNft(_nftTokenId, _nftToken, _bTokenId, _erc20Token);
require(!_nft.marks.isRepay && _nft.marks.isBorrow, "NFT status wrong");
_;
}
function setPause(bool _pause) public onlyOwner {
pause = _pause;
}
function setInterestRate(uint256 _interestRate) public isPause onlyOwner {
interestRate = _interestRate;
}
function setCycle(uint256 _cycle) public isPause onlyOwner {
cycle = _cycle;
}
function setEmergencyCycle(uint256 _emergencyCycle)
public
isPause
onlyOwner
{
emergencyCycle = _emergencyCycle;
}
function setWhiteList(IERC20[] memory _whiteList) public isPause onlyOwner {
whiteList = _whiteList;
}
function setFee(uint256 _fee) public isPause onlyOwner {
fee = _fee;
}
function getWhiteListLength() public view returns (uint256 length) {
length = whiteList.length;
}
function addWhiteList(IERC20 _address) public isPause onlyOwner {
whiteList.push(_address);
}
function _addNftAdr(IERC721 _nftToken) internal {
uint256 len = NftAdrList.length;
bool hasAdr = false;
for (uint256 index = 0; index < len; index++) {
if (_nftToken == NftAdrList[index]) {
hasAdr = true;
break;
}
}
if (!hasAdr) NftAdrList.push(_nftToken);
}
function getNftMapLength(IERC721 _nftToken)
public
view
returns (uint256 length)
{
length = NftMap[_nftToken].length;
}
function getNftAdrListLength() public view returns (uint256 length) {
length = NftAdrList.length;
}
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes memory data
) public override(ERC721Holder) returns (bytes4) {
emit NFTReceived(operator, from, tokenId, data);
return
bytes4(
keccak256("onERC721Received(address,address,uint256,bytes)")
);
}
// deposit NFT
function depositErc721(
uint256 _nftTokenId,
IERC721 _nftToken,
uint256 _amount,
IERC20 _erc20Token
) public isPause checkDebt(_amount) checkWhiteList(_erc20Token) {
bool isERC721 = IERC721(_nftToken).supportsInterface(0x80ac58cd);
require(isERC721, "Parameter _nftToken is not ERC721 contract address");
// mint bToken
uint256 _bTokenId = bToken.mint(msg.sender);
_addNftAdr(_nftToken);
MARK memory _mark = MARK(false, false, false);
// save collateral info
NftMap[_nftToken].push(
Nft({
holder: msg.sender,
tokenId: _nftTokenId,
nftToken: _nftToken,
amount: _amount,
erc20Token: _erc20Token,
bTokenId: _bTokenId,
borrowBlock: 0,
borrowTimestamp: 0,
emergencyTimestamp: 0,
repayAmount: 0,
lTokenId: 0,
marks: _mark
})
);
IERC721(_nftToken).safeTransferFrom(
msg.sender,
address(this),
_nftTokenId
);
emit DepositErc721(_nftTokenId, _nftToken, _amount, _erc20Token);
}
// Lend ERC20
function lendERC20(
uint256 _nftTokenId,
IERC721 _nftToken,
uint256 _amount,
IERC20 _erc20Token,
uint256 _bTokenId
) public isPause checkDebt(_amount) checkWhiteList(_erc20Token) {
Nft memory _nft =
_findNft(_nftTokenId, _nftToken, _bTokenId, _erc20Token);
require(!_nft.marks.isBorrow, "This collateral already borrowed");
// mint lToken
uint256 _lTokenId = lToken.mint(msg.sender);
// set collateral lTokenid
_setCollateralLTokenId(_nftTokenId, _nftToken, _bTokenId, _lTokenId);
// get lend amount
uint256 tempAmount =
calcLenderAmount(_nftTokenId, _nftToken, _bTokenId, _erc20Token);
require(_amount >= tempAmount, "The _amount is not match");
// get fee
uint256 _fee = _amount - _nft.amount;
IERC20(_erc20Token).safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
IERC20(_erc20Token).safeTransfer(owner(), _fee);
emit LendERC20(_nftTokenId, _nftToken, _amount, _erc20Token, _bTokenId);
// borrow action
_borrow(_nftTokenId, _nftToken, _erc20Token, _bTokenId);
}
function _borrow(
uint256 _nftTokenId,
IERC721 _nftToken,
IERC20 _erc20Token,
uint256 _bTokenId
) internal {
Nft memory _nft =
_findNft(_nftTokenId, _nftToken, _bTokenId, _erc20Token);
// change collateral status
_changeCollateralStatus(
_nftTokenId,
_nftToken,
true,
false,
false,
block.timestamp,
_nft.repayAmount,
_nft.emergencyTimestamp
);
// send erc20 token to collateral _nft.holder
IERC20(_erc20Token).safeTransfer(address(_nft.holder), _nft.amount);
emit Borrow(
_nftTokenId,
_nftToken,
_nft.amount,
_erc20Token,
_bTokenId
);
}
function repay(
uint256 _nftTokenId,
IERC721 _nftToken,
uint256 _amount,
IERC20 _erc20Token,
uint256 _bTokenId
) public isPause checkDebt(_amount) checkWhiteList(_erc20Token) {
Nft memory _nft =
_findNft(_nftTokenId, _nftToken, _bTokenId, _erc20Token);
// get repay amount
uint256 _repayAmount =
calcInterestRate(
_nftTokenId,
_nftToken,
_bTokenId,
_erc20Token,
true
);
require(_amount >= _repayAmount, "Wrong amount.");
// change collateral status
_changeCollateralStatus(
_nftTokenId,
_nftToken,
false,
true,
false,
_nft.borrowTimestamp,
_repayAmount,
_nft.emergencyTimestamp
);
// send erc20 token to contract
IERC20(_erc20Token).safeTransferFrom(
address(msg.sender),
address(this),
_repayAmount
);
emit Repay(
_nftTokenId,
_nftToken,
_repayAmount,
_erc20Token,
_bTokenId
);
}
function claimCollateral(
uint256 _nftTokenId,
IERC721 _nftToken,
IERC20 _erc20Token,
uint256 _bTokenId
) public isPause {
Nft memory _nft =
_findNft(_nftTokenId, _nftToken, _bTokenId, _erc20Token);
if (_nft.marks.isBorrow) {
require(_nft.marks.isRepay, "This debt is not repay");
}
_changeCollateralStatus(
_nftTokenId,
_nftToken,
false,
true,
true,
_nft.borrowTimestamp,
_nft.repayAmount,
_nft.emergencyTimestamp
);
// send bToken to contract for widthdraw collateral
IERC721(bToken).safeTransferFrom(msg.sender, address(0), _bTokenId);
// send collateral to msg.sender
IERC721(_nftToken).safeTransferFrom(
address(this),
msg.sender,
_nftTokenId
);
emit ClaimCollateral(_nftTokenId, _nftToken, _erc20Token, _bTokenId);
}
function lTokenClaimERC20(
uint256 _nftTokenId,
IERC721 _nftToken,
IERC20 _erc20Token,
uint256 _lTokenId,
uint256 _bTokenId
) public isPause checkWhiteList(_erc20Token) {
// check collateral holder has borrow
Nft memory _nft =
_findNft(_nftTokenId, _nftToken, _bTokenId, _erc20Token);
require(_nft.marks.isRepay, "This debt is not clear");
// send lToken to contract
IERC721(lToken).safeTransferFrom(msg.sender, address(0), _lTokenId);
// send erc20 token to msg.sender
IERC20(_erc20Token).safeTransfer(msg.sender, _nft.repayAmount);
emit LTokenClaimERC20(
_nftTokenId,
_nftToken,
_nft.repayAmount,
_erc20Token,
_lTokenId,
_bTokenId
);
}
function executeEmergency(
uint256 _nftTokenId,
IERC721 _nftToken,
IERC20 _erc20Token,
uint256 _lTokenId,
uint256 _bTokenId
)
public
isPause
checkCollateralStatus(_nftTokenId, _nftToken, _bTokenId, _erc20Token)
{
Nft memory _nft =
_findNft(_nftTokenId, _nftToken, _bTokenId, _erc20Token);
uint256 time = _nft.borrowTimestamp;
// An emergency can be triggered after 30 days
require(
(block.timestamp - time) > cycle,
"Can do not execute emergency."
);
// set trigger emergency timestamp for withdraw collateral
_changeCollateralStatus(
_nftTokenId,
_nftToken,
_nft.marks.isBorrow,
_nft.marks.isRepay,
_nft.marks.hasWithdraw,
_nft.borrowTimestamp,
_nft.repayAmount,
block.timestamp
);
// send lToken for verify
IERC721(lToken).safeTransferFrom(msg.sender, address(this), _lTokenId);
IERC721(lToken).safeTransferFrom(address(this), msg.sender, _lTokenId);
emit ExecuteEmergency(
_nftTokenId,
_nftToken,
_erc20Token,
_lTokenId,
_bTokenId
);
}
function liquidate(
uint256 _nftTokenId,
IERC721 _nftToken,
IERC20 _erc20Token,
uint256 _lTokenId,
uint256 _bTokenId
)
public
isPause
checkCollateralStatus(_nftTokenId, _nftToken, _bTokenId, _erc20Token)
{
Nft memory _nft =
_findNft(_nftTokenId, _nftToken, _bTokenId, _erc20Token);
// send lToken for verify
IERC721(lToken).safeTransferFrom(msg.sender, address(0), _lTokenId);
uint256 _emerTime = _nft.emergencyTimestamp;
// An emergency withdraw can be triggered after 15 days
require(
(block.timestamp - _emerTime) > emergencyCycle,
"Can do not liquidate."
);
// send collateral to lToken holder
IERC721(_nftToken).safeTransferFrom(
address(this),
msg.sender,
_nftTokenId
);
_changeCollateralStatus(
_nftTokenId,
_nftToken,
false,
true,
true,
_nft.borrowTimestamp,
_nft.repayAmount,
_nft.emergencyTimestamp
);
emit Liquidate(
_nftTokenId,
_nftToken,
_erc20Token,
_lTokenId,
_bTokenId
);
}
function _changeCollateralStatus(
uint256 _nftTokenId,
IERC721 _nftToken,
bool isBorrow,
bool isRepay,
bool hasWithdraw,
uint256 _borrowTimestamp,
uint256 _repayAmount,
uint256 _emergencyTimestamp
) internal {
Nft[] storage nftList = NftMap[_nftToken];
Nft storage nft;
bool _hasNft = false;
for (uint256 index = nftList.length - 1; index >= 0; index--) {
nft = nftList[index];
if (nft.tokenId == _nftTokenId && _nftToken == nft.nftToken) {
_hasNft = true;
nft.marks.isBorrow = isBorrow;
nft.marks.isRepay = isRepay;
nft.marks.hasWithdraw = hasWithdraw;
if (isBorrow) nft.borrowBlock = block.number;
nft.borrowTimestamp = _borrowTimestamp;
nft.repayAmount = _repayAmount;
nft.emergencyTimestamp = _emergencyTimestamp;
break;
}
}
require(_hasNft, "Not find this nft -> changeCollateralStatus");
}
function calcInterestRate(
uint256 _nftTokenId,
IERC721 _nftToken,
uint256 _bTokenId,
IERC20 _erc20Token,
bool _isRepay
) public view returns (uint256 repayAmount) {
uint256 _borrowBlock;
uint256 base = _isRepay ? 100 : 101;
Nft memory _nft =
_findNft(_nftTokenId, _nftToken, _bTokenId, _erc20Token);
// repayAmount = _nft.amount;
_borrowBlock = block.number - _nft.borrowBlock;
uint256 _interestRate =
(_borrowBlock * interestRate * _nft.amount) / 10**18;
// repayAmount = _interestRate + (_nft.amount / 100) * base;
repayAmount = _interestRate.add(_nft.amount.mul(base).div(100));
}
function calcLenderAmount(
uint256 _nftTokenId,
IERC721 _nftToken,
uint256 _bTokenId,
IERC20 _erc20Token
) public view returns (uint256 tempAmount) {
Nft memory _nft =
_findNft(_nftTokenId, _nftToken, _bTokenId, _erc20Token);
tempAmount = _nft.amount.mul(10000 + fee).div(10000); // tempAmount = (_nft.amount / 10000) * (10000 + fee);
}
function _setCollateralLTokenId(
uint256 _nftTokenId,
IERC721 _nftToken,
uint256 _bTokenId,
uint256 _lTokenId
) internal {
Nft[] storage nftList = NftMap[_nftToken];
Nft storage nft;
bool _hasNft = false;
for (uint256 index = nftList.length - 1; index >= 0; index--) {
nft = nftList[index];
if (
nft.tokenId == _nftTokenId &&
_nftToken == nft.nftToken &&
nft.bTokenId == _bTokenId
) {
_hasNft = true;
nft.lTokenId = _lTokenId;
break;
}
}
require(_hasNft, "Not find this nft -> _setCollateralLTokenId");
}
function _findNft(
uint256 _nftTokenId,
IERC721 _nftToken,
uint256 _bTokenId,
IERC20 _erc20Token
) internal view returns (Nft memory) {
bool _hasNft = false;
Nft[] memory nftList = NftMap[_nftToken];
Nft memory _nft;
for (uint256 index = nftList.length - 1; index >= 0; index--) {
_nft = nftList[index];
if (
_nft.tokenId == _nftTokenId &&
_nft.nftToken == _nftToken &&
_nft.bTokenId == _bTokenId &&
_nft.erc20Token == _erc20Token
) {
_hasNft = true;
break;
}
}
require(_hasNft, "Not find this nft -> _findNft");
return _nft;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract LenderToken is
ERC721URIStorage,
ERC721Enumerable,
Ownable,
ERC721Burnable
{
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
string public prefix = "http://app.kyoko.finance/ltoken/";
string public suffix = ".png";
constructor() ERC721("KyokoLToken", "KL") {}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, amount);
}
function mint(address player) public onlyOwner returns (uint256) {
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
string memory _index = uint2str(newItemId);
string memory _URI = strConcat(prefix, _index, suffix);
_mint(player, newItemId);
_setTokenURI(newItemId, _URI);
return newItemId;
}
function burn(uint256 tokenId) public virtual override(ERC721Burnable) {
super._burn(tokenId);
}
function _burn(uint256 tokenId)
internal
virtual
override(ERC721, ERC721URIStorage)
{
super._burn(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function tokenURI(uint256 tokenId)
public
view
virtual
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function uint2str(uint256 _i)
public
pure
returns (string memory _uintAsString)
{
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;
while (_i != 0) {
k = k - 1;
uint8 temp = (48 + uint8(_i - (_i / 10) * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
function strConcat(
string memory _a,
string memory _b,
string memory _c
) public pure returns (string memory) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
string memory ret = new string(_ba.length + _bb.length + _bc.length);
bytes memory bret = bytes(ret);
uint256 k = 0;
for (uint256 i = 0; i < _ba.length; i++) bret[k++] = _ba[i];
for (uint256 i = 0; i < _bb.length; i++) bret[k++] = _bb[i];
for (uint256 i = 0; i < _bc.length; i++) bret[k++] = _bc[i];
return string(ret);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "./extensions/IERC721Enumerable.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings 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.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC721).interfaceId
|| interfaceId == type(IERC721Metadata).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: '';
}
/**
* @dev Base URI for computing {tokenURI}. 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 = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "../../../utils/Context.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings 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];
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Receiver.sol";
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
*/
contract ERC721Holder is IERC721Receiver {
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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;`
*/
library Counters {
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;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface 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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
// 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) {
unchecked {
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) {
unchecked {
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) {
return a + b;
}
/**
* @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 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) {
return a * b;
}
/**
* @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.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
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) {
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) {
unchecked {
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.
*
* 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).
*
* 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) {
unchecked {
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) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
| check collateral holder has borrow send lToken to contract send erc20 token to msg.sender | function lTokenClaimERC20(
uint256 _nftTokenId,
IERC721 _nftToken,
IERC20 _erc20Token,
uint256 _lTokenId,
uint256 _bTokenId
) public isPause checkWhiteList(_erc20Token) {
Nft memory _nft =
_findNft(_nftTokenId, _nftToken, _bTokenId, _erc20Token);
require(_nft.marks.isRepay, "This debt is not clear");
IERC721(lToken).safeTransferFrom(msg.sender, address(0), _lTokenId);
IERC20(_erc20Token).safeTransfer(msg.sender, _nft.repayAmount);
emit LTokenClaimERC20(
_nftTokenId,
_nftToken,
_nft.repayAmount,
_erc20Token,
_lTokenId,
_bTokenId
);
}
| 1,710,514 | [
1,
1893,
4508,
2045,
287,
10438,
711,
29759,
1366,
328,
1345,
358,
6835,
1366,
6445,
71,
3462,
1147,
358,
1234,
18,
15330,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
328,
1345,
9762,
654,
39,
3462,
12,
203,
3639,
2254,
5034,
389,
82,
1222,
1345,
548,
16,
203,
3639,
467,
654,
39,
27,
5340,
389,
82,
1222,
1345,
16,
203,
3639,
467,
654,
39,
3462,
389,
12610,
3462,
1345,
16,
203,
3639,
2254,
5034,
389,
80,
1345,
548,
16,
203,
3639,
2254,
5034,
389,
70,
1345,
548,
203,
565,
262,
1071,
353,
19205,
866,
13407,
682,
24899,
12610,
3462,
1345,
13,
288,
203,
3639,
423,
1222,
3778,
389,
82,
1222,
273,
203,
5411,
389,
4720,
50,
1222,
24899,
82,
1222,
1345,
548,
16,
389,
82,
1222,
1345,
16,
389,
70,
1345,
548,
16,
389,
12610,
3462,
1345,
1769,
203,
3639,
2583,
24899,
82,
1222,
18,
17439,
18,
291,
426,
10239,
16,
315,
2503,
18202,
88,
353,
486,
2424,
8863,
203,
3639,
467,
654,
39,
27,
5340,
12,
80,
1345,
2934,
4626,
5912,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
20,
3631,
389,
80,
1345,
548,
1769,
203,
3639,
467,
654,
39,
3462,
24899,
12610,
3462,
1345,
2934,
4626,
5912,
12,
3576,
18,
15330,
16,
389,
82,
1222,
18,
266,
10239,
6275,
1769,
203,
3639,
3626,
511,
1345,
9762,
654,
39,
3462,
12,
203,
5411,
389,
82,
1222,
1345,
548,
16,
203,
5411,
389,
82,
1222,
1345,
16,
203,
5411,
389,
82,
1222,
18,
266,
10239,
6275,
16,
203,
5411,
389,
12610,
3462,
1345,
16,
203,
5411,
389,
80,
1345,
548,
16,
203,
5411,
389,
70,
1345,
548,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.18;
library SafeMath {
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;
}
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnerChanged(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function changeOwner(address _newOwner) onlyOwner public {
require(_newOwner != address(0));
OwnerChanged(owner, _newOwner);
owner = _newOwner;
}
}
interface Token {
function transfer(address _to, uint256 _value) public;
function balanceOf(address _owner) public constant returns (uint256 balance);
//function transfer(address _to, uint256 _value) public returns (bool success);
//event Transfer(address indexed _from, address indexed _to, uint256 _value);
}
contract Batchdrop is Ownable {
using SafeMath for uint256;
event TransferToken(address indexed from, address indexed to, uint256 value);
Token public standardToken;
// List of admins
mapping (address => bool) public contractAdmins;
mapping (address => bool) public userTransfered;
uint256 public totalUserTransfered;
function Batchdrop(address _owner) public {
require(_owner != address(0));
owner = _owner;
owner = msg.sender; //for test
}
function setContractToken (address _addressContract) public onlyOwner {
require(_addressContract != address(0));
standardToken = Token(_addressContract);
totalUserTransfered = 0;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return standardToken.balanceOf(_owner);
}
modifier onlyOwnerOrAdmin() {
require(msg.sender == owner || contractAdmins[msg.sender]);
_;
}
/**
* @dev Add an contract admin
*/
function setContractAdmin(address _admin, bool _isAdmin) public onlyOwner {
contractAdmins[_admin] = _isAdmin;
}
/* Batch token transfer. Used by contract creator to distribute initial tokens to holders */
function batchdrop(address[] _recipients, uint256[] _values) external onlyOwnerOrAdmin returns (bool) {
require( _recipients.length > 0 && _recipients.length == _values.length);
uint256 total = 0;
for(uint i = 0; i < _values.length; i++){
total = total.add(_values[i]);
}
require(total <= standardToken.balanceOf(msg.sender));
for(uint j = 0; j < _recipients.length; j++){
standardToken.transfer(_recipients[j], _values[j]);
totalUserTransfered = totalUserTransfered.add(1);
userTransfered[_recipients[j]] = true;
TransferToken(msg.sender, _recipients[j], _values[j]);
}
return true;
}
} | Batch token transfer. Used by contract creator to distribute initial tokens to holders */ | function batchdrop(address[] _recipients, uint256[] _values) external onlyOwnerOrAdmin returns (bool) {
require( _recipients.length > 0 && _recipients.length == _values.length);
uint256 total = 0;
for(uint i = 0; i < _values.length; i++){
total = total.add(_values[i]);
}
require(total <= standardToken.balanceOf(msg.sender));
for(uint j = 0; j < _recipients.length; j++){
standardToken.transfer(_recipients[j], _values[j]);
totalUserTransfered = totalUserTransfered.add(1);
userTransfered[_recipients[j]] = true;
TransferToken(msg.sender, _recipients[j], _values[j]);
}
return true;
}
| 8,049,262 | [
1,
4497,
1147,
7412,
18,
10286,
635,
6835,
11784,
358,
25722,
2172,
2430,
358,
366,
4665,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
2581,
7285,
12,
2867,
8526,
389,
27925,
16,
2254,
5034,
8526,
389,
2372,
13,
3903,
1338,
5541,
1162,
4446,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
389,
27925,
18,
2469,
405,
374,
597,
389,
27925,
18,
2469,
422,
389,
2372,
18,
2469,
1769,
203,
3639,
2254,
5034,
2078,
273,
374,
31,
203,
3639,
364,
12,
11890,
277,
273,
374,
31,
277,
411,
389,
2372,
18,
2469,
31,
277,
27245,
95,
203,
5411,
2078,
273,
2078,
18,
1289,
24899,
2372,
63,
77,
19226,
203,
3639,
289,
203,
3639,
2583,
12,
4963,
1648,
4529,
1345,
18,
12296,
951,
12,
3576,
18,
15330,
10019,
203,
3639,
364,
12,
11890,
525,
273,
374,
31,
525,
411,
389,
27925,
18,
2469,
31,
525,
27245,
95,
203,
5411,
4529,
1345,
18,
13866,
24899,
27925,
63,
78,
6487,
389,
2372,
63,
78,
19226,
203,
5411,
2078,
1299,
5912,
329,
273,
2078,
1299,
5912,
329,
18,
1289,
12,
21,
1769,
203,
5411,
729,
5912,
329,
63,
67,
27925,
63,
78,
13563,
273,
638,
31,
203,
5411,
12279,
1345,
12,
3576,
18,
15330,
16,
389,
27925,
63,
78,
6487,
389,
2372,
63,
78,
19226,
203,
3639,
289,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/42/0x6c0b88641221e647B875d76A758885bCAd19eFF7/sources/CustomConfig.sol | * @dev Set the limit of tokens allowed to be transferred monthly. param _newMonthlyLimit The new monthly limit of tokens/ | function setMonthlyLimit(uint256 _newMonthlyLimit) public onlyOwner {
monthlyLimit = _newMonthlyLimit;
emit MonthlyLimitUpdated(_newMonthlyLimit);
}
| 3,402,614 | [
1,
694,
326,
1800,
434,
2430,
2935,
358,
506,
906,
4193,
31114,
18,
225,
579,
389,
2704,
5445,
715,
3039,
1021,
394,
31114,
1800,
434,
2430,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
444,
5445,
715,
3039,
12,
11890,
5034,
389,
2704,
5445,
715,
3039,
13,
1071,
1338,
5541,
288,
203,
3639,
31114,
3039,
273,
389,
2704,
5445,
715,
3039,
31,
203,
3639,
3626,
10337,
715,
3039,
7381,
24899,
2704,
5445,
715,
3039,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity =0.6.12;
pragma experimental ABIEncoderV2;
// import './interfaces/IFeSwapFactory.sol';
pragma solidity =0.6.12;
interface IFeSwapFactory {
event PairCreated(address indexed tokenA, address indexed tokenB, address pairAAB, address pairABB, uint);
function feeTo() external view returns (address);
function getFeeInfo() external view returns (address, uint256);
function factoryAdmin() external view returns (address);
function routerFeSwap() external view returns (address);
function rateTriggerFactory() external view returns (uint64);
function rateCapArbitrage() external view returns (uint64);
function rateProfitShare() external view returns (uint64);
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 createUpdatePair(address tokenA, address tokenB, address pairOwner, uint256 rateTrigger) external returns (address pairAAB,address pairABB);
function setFeeTo(address) external;
function setFactoryAdmin(address) external;
function setRouterFeSwap(address) external;
function configFactory(uint64, uint64, uint64) external;
function managePair(address, address, address, address) external;
}
// import './libraries/TransferHelper.sol';
pragma solidity =0.6.12;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// import './interfaces/IFeSwapRouter.sol';
pragma solidity =0.6.12;
interface IFeSwapRouter {
struct AddLiquidityParams {
address tokenA;
address tokenB;
uint amountADesired;
uint amountBDesired;
uint amountAMin;
uint amountBMin;
uint ratio;
}
struct AddLiquidityETHParams {
address token;
uint amountTokenDesired;
uint amountTokenMin;
uint amountETHMin;
uint ratio;
}
struct RemoveLiquidityParams {
address tokenA;
address tokenB;
uint liquidityAAB;
uint liquidityABB;
uint amountAMin;
uint amountBMin;
}
struct Signature {
uint8 v;
bytes32 r;
bytes32 s;
}
function factory() external pure returns (address);
function feswaNFT() external pure returns (address);
function WETH() external pure returns (address);
function ManageFeswaPair(
uint256 tokenID,
address pairOwner,
uint256 rateTrigger
) external returns (address pairAAB, address pairABB);
function addLiquidity(
AddLiquidityParams calldata addParams,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidityAAB, uint liquidityABB);
function addLiquidityETH(
AddLiquidityETHParams calldata addParams,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidityTTE, uint liquidityTEE);
function removeLiquidity(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline,
bool approveMax,
Signature calldata sigAAB,
Signature calldata sigABB
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline,
bool approveMax,
Signature calldata sigTTE,
Signature calldata sigTEE
) external returns (uint amountToken, uint amountETH);
function removeLiquidityETHFeeOnTransfer(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitFeeOnTransfer(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline,
bool approveMax,
Signature calldata sigTTE,
Signature calldata sigTEE
) external returns (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 swapExactTokensForTokensFeeOnTransfer(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensFeeOnTransfer(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHFeeOnTransfer(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
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 estimateAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function estimateAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// import './libraries/FeSwapLibrary.sol';
pragma solidity =0.6.12;
// import '../interfaces/IFeSwapPair.sol';
pragma solidity =0.6.12;
// import './IFeSwapERC20.sol';
pragma solidity =0.6.12;
interface IFeSwapERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
interface IFeSwapPair is IFeSwapERC20 {
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 amount1Out, address indexed to );
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function pairOwner() external view returns (address);
function tokenIn() external view returns (address);
function tokenOut() external view returns (address);
function getReserves() external view returns ( uint112 _reserveIn, uint112 _reserveOut,
uint32 _blockTimestampLast, uint _rateTriggerArbitrage);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function rateTriggerArbitrage() 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 amountOut, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address, address, address, uint) external;
function setOwner(address _pairOwner) external;
function adjusArbitragetRate(uint newRate) external;
}
// import '../interfaces/IFeSwapFactory.sol';
// import './TransferHelper.sol';
// import "./SafeMath.sol";
pragma solidity =0.6.12;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
pragma solidity =0.6.12;
// import '../interfaces/IFeSwapPair.sol';
// import '../interfaces/IFeSwapFactory.sol';
// import './TransferHelper.sol';
// import "./SafeMath.sol";
library FeSwapLibrary {
using SafeMath for uint;
// 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) {
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(tokenA, tokenB)),
hex'5ff2250d3f849930264d443f14a482794b12bd40ac16b457def9522f050665da' // init code hash // save 9916 gas
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB)
internal view returns (uint reserveA, uint reserveB, address pair, uint rateTriggerArbitrage) {
pair = pairFor(factory, tokenA, tokenB);
(reserveA, reserveB, , rateTriggerArbitrage) = IFeSwapPair(pair).getReserves();
}
// 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, 'FeSwapLibrary: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'FeSwapLibrary: 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, 'FeSwapLibrary: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'FeSwapLibrary: INSUFFICIENT_LIQUIDITY');
uint numerator = amountIn.mul(reserveOut);
uint denominator = reserveIn.add(amountIn);
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, 'FeSwapLibrary: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'FeSwapLibrary: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut);
uint denominator = reserveOut.sub(amountOut);
amountIn = (numerator.add(denominator)) / denominator;
}
function arbitragePairPools(address factory, address tokenA, address tokenB)
internal returns (uint reserveIn, uint reserveOut, address pair) {
(reserveIn, reserveOut, pair, ) = getReserves(factory, tokenA, tokenB);
(uint reserveInMate, uint reserveOutMate, address PairMate, uint rateTriggerArbitrage) = getReserves(factory, tokenB, tokenA);
uint productIn = uint(reserveIn).mul(reserveInMate);
uint productOut = uint(reserveOut).mul(reserveOutMate);
if(productIn.mul(10000) > productOut.mul(rateTriggerArbitrage)){
productIn = productIn.sub(productOut); // productIn are re-used
uint totalTokenA = (uint(reserveIn).add(reserveOutMate)).mul(2);
uint totalTokenB = (uint(reserveOut).add(reserveInMate)).mul(2);
TransferHelper.safeTransferFrom(tokenA, pair, PairMate, productIn / totalTokenB);
TransferHelper.safeTransferFrom(tokenB, PairMate, pair, productIn / totalTokenA);
IFeSwapPair(pair).sync();
IFeSwapPair(PairMate).sync();
(reserveIn, reserveOut, ,) = getReserves(factory, tokenA, tokenB);
}
}
function culculatePairPools(address factory, address tokenA, address tokenB) internal view returns (uint reserveIn, uint reserveOut, address pair) {
(reserveIn, reserveOut, pair, ) = getReserves(factory, tokenA, tokenB);
(uint reserveInMate, uint reserveOutMate, , uint rateTriggerArbitrage) = getReserves(factory, tokenB, tokenA);
uint productIn = uint(reserveIn).mul(reserveInMate);
uint productOut = uint(reserveOut).mul(reserveOutMate);
if(productIn.mul(10000) > productOut.mul(rateTriggerArbitrage)){
productIn = productIn.sub(productOut);
uint totalTokenA = (uint(reserveIn).add(reserveOutMate)).mul(2);
uint totalTokenB = (uint(reserveOut).add(reserveInMate)).mul(2);
reserveIn = reserveIn.sub(productIn / totalTokenB);
reserveOut = reserveOut.add(productIn / totalTokenA);
}
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] calldata path) internal returns (address firstPair, uint[] memory amounts) {
require(path.length >= 2, 'FeSwapLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i = 0; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut, address _firstPair) = arbitragePairPools(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
if ( i == 0 ) firstPair = _firstPair;
}
}
// performs aritrage beforehand
function executeArbitrage(address factory, address[] calldata path) internal {
require(path.length >= 2, 'FeSwapLibrary: INVALID_PATH');
for (uint i = 0; i < path.length - 1; i++) {
arbitragePairPools(factory, path[i], path[i + 1]);
}
}
// performs chained estimateAmountsOut calculations on any number of pairs
function estimateAmountsOut(address factory, uint amountIn, address[] calldata path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'FeSwapLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i = 0; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut, ) = culculatePairPools(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[] calldata path) internal returns (address firstPair, uint[] memory amounts) {
require(path.length >= 2, 'FeSwapLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
uint reserveIn;
uint reserveOut;
for (uint i = path.length - 1; i > 0; i--) {
(reserveIn, reserveOut, firstPair) = arbitragePairPools(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
function estimateAmountsIn(address factory, uint amountOut, address[] calldata path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'FeSwapLibrary: 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, ) = culculatePairPools(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// import './libraries/SafeMath.sol';
// import './interfaces/IERC20.sol';
pragma solidity =0.6.12;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
// import './interfaces/IWETH.sol';
pragma solidity =0.6.12;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
// import './interfaces/IFeswaNFT.sol';
pragma solidity =0.6.12;
enum PoolRunningPhase {
BidToStart,
BidPhase,
BidDelaying,
BidSettled,
PoolHolding,
PoolForSale
}
struct FeswaPairNFT {
address tokenA;
address tokenB;
uint256 currentPrice;
uint64 timeCreated;
uint64 lastBidTime;
PoolRunningPhase poolState;
}
interface IFeswaNFT {
// Views
function ownerOf(uint256 tokenId) external view returns (address owner);
function getPoolInfo(uint256 tokenId) external view returns (address, FeswaPairNFT memory);
}
// import './interfaces/IFeSwapFactory.sol';
// import './libraries/TransferHelper.sol';
// import './interfaces/IFeSwapRouter.sol';
// import './libraries/FeSwapLibrary.sol';
// import './libraries/SafeMath.sol';
// import './interfaces/IERC20.sol';
// import './interfaces/IWETH.sol';
// import './interfaces/IFeswaNFT.sol';
contract FeSwapRouter is IFeSwapRouter{
using SafeMath for uint;
address public immutable override factory;
address public immutable override feswaNFT;
address public immutable override WETH;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'FeSwapRouter: EXPIRED');
_;
}
constructor(address _factory, address _feswaNFT, address _WETH) public {
factory = _factory;
feswaNFT = _feswaNFT;
WETH = _WETH;
}
receive() external payable {
assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}
// **** CREATE SWAP PAIR ****
function ManageFeswaPair( uint256 tokenID, address pairOwner, uint256 rateTrigger )
external virtual override
returns (address pairAAB, address pairABB)
{
(address nftOwner, FeswaPairNFT memory NftBidInfo) = IFeswaNFT(feswaNFT).getPoolInfo(tokenID);
require(msg.sender == nftOwner, 'FeSwap: NOT TOKEN OWNER');
require(NftBidInfo.poolState >= PoolRunningPhase.BidSettled, 'FeSwap: NOT ALLOWED');
(address tokenA, address tokenB) = (NftBidInfo.tokenA, NftBidInfo.tokenB);
(pairAAB, pairABB) = IFeSwapFactory(factory).createUpdatePair(tokenA, tokenB, pairOwner, rateTrigger);
}
// **** ADD LIQUIDITY ****
function _addLiquidity( address tokenIn,
address tokenOut,
uint amountInDesired,
uint amountOutDesired,
uint amountInMin,
uint amountOutMin
) internal virtual view returns (uint amountIn, uint amountOut, address pair) {
pair = FeSwapLibrary.pairFor(factory, tokenIn, tokenOut);
require(pair != address(0), 'FeSwap: NOT CREATED');
(uint reserveIn, uint reserveOut, ,) = IFeSwapPair(pair).getReserves();
if (reserveIn == 0 && reserveOut == 0) {
(amountIn, amountOut) = (amountInDesired, amountOutDesired);
} else {
uint amountOutOptimal = FeSwapLibrary.quote(amountInDesired, reserveIn, reserveOut);
if (amountOutOptimal <= amountOutDesired) {
require(amountOutOptimal >= amountOutMin, 'FeSwap: LESS_OUT_AMOUNT');
(amountIn, amountOut) = (amountInDesired, amountOutOptimal);
} else {
uint amountInOptimal = FeSwapLibrary.quote(amountOutDesired, reserveOut, reserveIn);
assert(amountInOptimal <= amountInDesired);
require(amountInOptimal >= amountInMin, 'FeSwap: LESS_IN_AMOUNT');
(amountIn, amountOut) = (amountInOptimal, amountOutDesired);
}
}
}
function addLiquidity( AddLiquidityParams calldata addParams,
address to,
uint deadline )
external virtual override ensure(deadline)
returns (uint amountA, uint amountB, uint liquidityAAB, uint liquidityABB)
{
require(addParams.ratio <= 100, 'FeSwap: RATIO EER');
if(addParams.ratio != uint(0)) {
address pairA2B;
uint liquidityA = addParams.amountADesired.mul(addParams.ratio)/100;
uint liquidityB = addParams.amountBDesired.mul(addParams.ratio)/100;
uint amountAMin = addParams.amountAMin.mul(addParams.ratio)/100;
uint amountBMin = addParams.amountBMin.mul(addParams.ratio)/100;
(amountA, amountB, pairA2B) =
_addLiquidity(addParams.tokenA, addParams.tokenB, liquidityA, liquidityB, amountAMin, amountBMin);
TransferHelper.safeTransferFrom(addParams.tokenA, msg.sender, pairA2B, amountA);
TransferHelper.safeTransferFrom(addParams.tokenB, msg.sender, pairA2B, amountB);
liquidityAAB = IFeSwapPair(pairA2B).mint(to);
}
if(addParams.ratio != uint(100)) {
address pairB2A;
uint liquidityA = addParams.amountADesired - amountA;
uint liquidityB = addParams.amountBDesired - amountB;
uint amountAMin = (addParams.amountAMin > amountA) ? (addParams.amountAMin - amountA) : 0 ;
uint amountBMin = (addParams.amountBMin > amountB) ? (addParams.amountBMin - amountB) : 0 ;
(liquidityB, liquidityA, pairB2A) =
_addLiquidity(addParams.tokenB, addParams.tokenA, liquidityB, liquidityA, amountBMin, amountAMin);
TransferHelper.safeTransferFrom(addParams.tokenA, msg.sender, pairB2A, liquidityA);
TransferHelper.safeTransferFrom(addParams.tokenB, msg.sender, pairB2A, liquidityB);
liquidityABB = IFeSwapPair(pairB2A).mint(to);
amountA += liquidityA;
amountB += liquidityB;
}
}
function addLiquidityETH( AddLiquidityETHParams calldata addParams,
address to,
uint deadline )
external virtual override payable ensure(deadline)
returns (uint amountToken, uint amountETH, uint liquidityTTE, uint liquidityTEE)
{
require(addParams.ratio <= 100, 'FeSwap: RATIO EER');
if(addParams.ratio != uint(0)) {
address pairTTE;
uint liquidityToken = addParams.amountTokenDesired.mul(addParams.ratio)/100;
uint liquidityETH = msg.value.mul(addParams.ratio)/100;
uint amountTokenMin = addParams.amountTokenMin.mul(addParams.ratio)/100;
uint amountETHMin = addParams.amountETHMin.mul(addParams.ratio)/100;
(amountToken, amountETH, pairTTE) =
_addLiquidity(addParams.token, WETH, liquidityToken, liquidityETH, amountTokenMin, amountETHMin);
TransferHelper.safeTransferFrom(addParams.token, msg.sender, pairTTE, amountToken);
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pairTTE, amountETH));
liquidityTTE = IFeSwapPair(pairTTE).mint(to);
}
if(addParams.ratio != uint(100)){
address pairTEE;
uint liquidityToken = addParams.amountTokenDesired - amountToken;
uint liquidityETH = msg.value - amountETH;
uint amountTokenMin = (addParams.amountTokenMin > amountToken) ? (addParams.amountTokenMin - amountToken) : 0 ;
uint amountETHMin = (addParams.amountETHMin > amountETH) ? (addParams.amountETHMin - amountETH) : 0 ;
(liquidityETH, liquidityToken, pairTEE) =
_addLiquidity(WETH, addParams.token, liquidityETH, liquidityToken, amountETHMin, amountTokenMin);
TransferHelper.safeTransferFrom(addParams.token, msg.sender, pairTEE, liquidityToken);
IWETH(WETH).deposit{value: liquidityETH}();
assert(IWETH(WETH).transfer(pairTEE, liquidityETH));
liquidityTEE = IFeSwapPair(pairTEE).mint(to);
amountToken += liquidityToken;
amountETH += liquidityETH;
}
// refund dust eth, if any
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {
if(removeParams.liquidityAAB != uint(0)) {
address pairAAB = FeSwapLibrary.pairFor(factory, removeParams.tokenA, removeParams.tokenB);
IFeSwapPair(pairAAB).transferFrom(msg.sender, pairAAB, removeParams.liquidityAAB); // send liquidity to pair
(amountA, amountB) = IFeSwapPair(pairAAB).burn(to);
}
if(removeParams.liquidityABB != uint(0)) {
address pairABB = FeSwapLibrary.pairFor(factory, removeParams.tokenB, removeParams.tokenA);
IFeSwapPair(pairABB).transferFrom(msg.sender, pairABB, removeParams.liquidityABB); // send liquidity to pair
(uint amountB0, uint amountA0) = IFeSwapPair(pairABB).burn(to);
amountA += amountA0;
amountB += amountB0;
}
require(amountA >= removeParams.amountAMin, 'FeSwapRouter: INSUFFICIENT_A_AMOUNT');
require(amountB >= removeParams.amountBMin, 'FeSwapRouter: INSUFFICIENT_B_AMOUNT');
}
function removeLiquidityETH(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {
require(removeParams.tokenB == WETH, 'FeSwap: WRONG WETH');
(amountToken, amountETH) = removeLiquidity(
removeParams,
address(this),
deadline
);
TransferHelper.safeTransfer(removeParams.tokenA, to, amountToken);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removePermit(
RemoveLiquidityParams calldata removeParams,
uint deadline,
bool approveMax,
Signature calldata sigAAB,
Signature calldata sigABB
) internal {
if(sigAAB.s != 0){
address pairAAB = FeSwapLibrary.pairFor(factory, removeParams.tokenA, removeParams.tokenB);
uint value = approveMax ? uint(-1) : removeParams.liquidityAAB;
IFeSwapPair(pairAAB).permit(msg.sender, address(this), value, deadline, sigAAB.v, sigAAB.r, sigAAB.s);
}
if(sigABB.s != 0){
address pairABB = FeSwapLibrary.pairFor(factory, removeParams.tokenB, removeParams.tokenA);
uint value = approveMax ? uint(-1) : removeParams.liquidityABB;
IFeSwapPair(pairABB).permit(msg.sender, address(this), value, deadline, sigABB.v, sigABB.r, sigABB.s);
}
}
function removeLiquidityWithPermit(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline,
bool approveMax,
Signature calldata sigAAB,
Signature calldata sigABB
) external virtual override returns (uint amountA, uint amountB) {
removePermit(removeParams, deadline, approveMax, sigAAB, sigABB);
(amountA, amountB) = removeLiquidity(removeParams, to, deadline);
}
function removeLiquidityETHWithPermit(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline,
bool approveMax,
Signature calldata sigTTE,
Signature calldata sigTEE
) external virtual override returns (uint amountToken, uint amountETH) {
removePermit(removeParams, deadline, approveMax, sigTTE, sigTEE);
(amountToken, amountETH) = removeLiquidityETH(removeParams, to, deadline);
}
// **** REMOVE LIQUIDITY (supporting deflation tokens) ****
function removeLiquidityETHFeeOnTransfer(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountETH) {
require(removeParams.tokenB == WETH, 'FeSwap: WRONG WETH');
uint amountToken;
uint balanceToken;
(amountToken, amountETH) = removeLiquidity( removeParams,
address(this),
deadline );
balanceToken = IERC20(removeParams.tokenA).balanceOf(address(this));
if(balanceToken < amountToken) amountToken = balanceToken;
TransferHelper.safeTransfer(removeParams.tokenA, to, amountToken);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityETHWithPermitFeeOnTransfer(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline,
bool approveMax,
Signature calldata sigTTE,
Signature calldata sigTEE
) external virtual override returns (uint amountETH) {
removePermit(removeParams, deadline, approveMax, sigTTE, sigTEE);
amountETH = removeLiquidityETHFeeOnTransfer(removeParams, to, deadline);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i = 0; i < path.length - 1; i++) {
(address tokenInput, address tokenOutput) = (path[i], path[i + 1]);
uint amountOut = amounts[i + 1];
address to = i < path.length - 2 ? FeSwapLibrary.pairFor(factory, tokenOutput, path[i + 2]) : _to;
IFeSwapPair(FeSwapLibrary.pairFor(factory, tokenInput, tokenOutput))
.swap(amountOut, to, new bytes(0));
}
}
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
address firstPair;
(firstPair, amounts) = FeSwapLibrary.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'FeSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(path[0], msg.sender, firstPair , amountIn);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
address firstPair;
uint amountsTokenIn;
(firstPair, amounts) = FeSwapLibrary.getAmountsIn(factory, amountOut, path);
amountsTokenIn = amounts[0];
require(amountsTokenIn <= amountInMax, 'FeSwapRouter: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(path[0], msg.sender, firstPair, amountsTokenIn);
_swap(amounts, path, to);
}
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external virtual override payable ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'FeSwapRouter: INVALID_PATH');
address firstPair;
uint amountsETHIn = msg.value;
(firstPair, amounts) = FeSwapLibrary.getAmountsOut(factory, amountsETHIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'FeSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).deposit{value: amountsETHIn}();
assert(IWETH(WETH).transfer(firstPair, amountsETHIn));
_swap(amounts, path, to);
}
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external virtual override ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'FeSwapRouter: INVALID_PATH');
address firstPair;
(firstPair, amounts) = FeSwapLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'FeSwapRouter: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(path[0], msg.sender, firstPair, amounts[0]);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external virtual override ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'FeSwapRouter: INVALID_PATH');
address firstPair;
uint amountsETHOut;
(firstPair, amounts) = FeSwapLibrary.getAmountsOut(factory, amountIn, path);
amountsETHOut = amounts[amounts.length - 1];
require(amountsETHOut >= amountOutMin, 'FeSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(path[0], msg.sender, firstPair, amountIn);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amountsETHOut);
TransferHelper.safeTransferETH(to, amountsETHOut);
}
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external virtual override payable ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'FeSwapRouter: INVALID_PATH');
address firstPair;
uint amountsETHIn;
(firstPair, amounts) = FeSwapLibrary.getAmountsIn(factory, amountOut, path);
amountsETHIn = amounts[0];
require(amountsETHIn <= msg.value, 'FeSwapRouter: EXCESSIVE_INPUT_AMOUNT');
IWETH(WETH).deposit{value: amountsETHIn}();
assert(IWETH(WETH).transfer(firstPair, amountsETHIn));
_swap(amounts, path, to);
// refund dust eth, if any
if (msg.value > amountsETHIn) TransferHelper.safeTransferETH(msg.sender, msg.value - amountsETHIn);
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapTokensFeeOnTransfer(address[] memory path, address _to) internal virtual {
for (uint i = 0; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(uint reserveInput, uint reserveOutput, address pair, ) = FeSwapLibrary.getReserves(factory, input, output);
uint amountInput = IERC20(input).balanceOf(pair).sub(reserveInput);
uint amountOutput = FeSwapLibrary.getAmountOut(amountInput, reserveInput, reserveOutput);
address to = i < path.length - 2 ? FeSwapLibrary.pairFor(factory, output, path[i + 2]) : _to;
IFeSwapPair(pair).swap(amountOutput, to, new bytes(0));
}
}
function swapExactTokensForTokensFeeOnTransfer(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) {
FeSwapLibrary.executeArbitrage(factory, path);
TransferHelper.safeTransferFrom(
path[0], msg.sender, FeSwapLibrary.pairFor(factory, path[0], path[1]), amountIn
);
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapTokensFeeOnTransfer(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'FeSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactETHForTokensFeeOnTransfer(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override payable ensure(deadline) {
require(path[0] == WETH, 'FeSwapRouter: INVALID_PATH');
FeSwapLibrary.executeArbitrage(factory, path);
uint amountIn = msg.value;
IWETH(WETH).deposit{value: amountIn}();
assert(IWETH(WETH).transfer(FeSwapLibrary.pairFor(factory, path[0], path[1]), amountIn));
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapTokensFeeOnTransfer(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'FeSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactTokensForETHFeeOnTransfer(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) {
require(path[path.length - 1] == WETH, 'FeSwapRouter: INVALID_PATH');
FeSwapLibrary.executeArbitrage(factory, path);
TransferHelper.safeTransferFrom(
path[0], msg.sender, FeSwapLibrary.pairFor(factory, path[0], path[1]), amountIn
);
_swapTokensFeeOnTransfer(path, address(this));
uint amountOut = IERC20(WETH).balanceOf(address(this));
require(amountOut >= amountOutMin, 'FeSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
function quote(uint amountA, uint reserveA, uint reserveB)
public pure virtual override returns (uint amountB)
{
return FeSwapLibrary.quote(amountA, reserveA, reserveB);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
public pure virtual override returns (uint amountOut)
{
return FeSwapLibrary.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
public pure virtual override returns (uint amountIn)
{
return FeSwapLibrary.getAmountIn(amountOut, reserveIn, reserveOut);
}
function estimateAmountsOut(uint amountIn, address[] calldata path)
public view virtual override returns (uint[] memory amounts)
{
return FeSwapLibrary.estimateAmountsOut(factory, amountIn, path);
}
function estimateAmountsIn(uint amountOut, address[] calldata path)
public view virtual override returns (uint[] memory amounts)
{
return FeSwapLibrary.estimateAmountsIn(factory, amountOut, path);
}
} | import '../interfaces/IFeSwapFactory.sol'; import './TransferHelper.sol'; import "./SafeMath.sol"; a library for performing overflow-safe math, courtesy of DappHub (https:github.com/dapphub/ds-math) | library SafeMath {
function factory() external pure returns (address);
function feswaNFT() external pure returns (address);
function WETH() external pure returns (address);
function ManageFeswaPair(
uint256 tokenID,
address pairOwner,
uint256 rateTrigger
) external returns (address pairAAB, address pairABB);
function addLiquidity(
AddLiquidityParams calldata addParams,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidityAAB, uint liquidityABB);
function addLiquidityETH(
AddLiquidityETHParams calldata addParams,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidityTTE, uint liquidityTEE);
function removeLiquidity(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline,
bool approveMax,
Signature calldata sigAAB,
Signature calldata sigABB
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline,
bool approveMax,
Signature calldata sigTTE,
Signature calldata sigTEE
) external returns (uint amountToken, uint amountETH);
function removeLiquidityETHFeeOnTransfer(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitFeeOnTransfer(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline,
bool approveMax,
Signature calldata sigTTE,
Signature calldata sigTEE
) external returns (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 swapExactTokensForTokensFeeOnTransfer(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensFeeOnTransfer(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHFeeOnTransfer(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
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 estimateAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function estimateAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
pragma solidity =0.6.12;
pragma solidity =0.6.12;
pragma solidity =0.6.12;
}
}
pragma solidity =0.6.12;
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');
}
}
| 6,066,713 | [
1,
5666,
25226,
15898,
19,
45,
2954,
12521,
1733,
18,
18281,
13506,
1930,
12871,
5912,
2276,
18,
18281,
13506,
1930,
25165,
9890,
10477,
18,
18281,
14432,
279,
5313,
364,
14928,
9391,
17,
4626,
4233,
16,
21833,
1078,
93,
434,
463,
2910,
8182,
261,
4528,
30,
6662,
18,
832,
19,
6223,
844,
373,
19,
2377,
17,
15949,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
12083,
14060,
10477,
288,
203,
565,
445,
3272,
1435,
3903,
16618,
1135,
261,
2867,
1769,
203,
565,
445,
284,
281,
91,
6491,
4464,
1435,
3903,
16618,
1135,
261,
2867,
1769,
203,
565,
445,
678,
1584,
44,
1435,
3903,
16618,
1135,
261,
2867,
1769,
203,
203,
565,
445,
24247,
42,
281,
91,
69,
4154,
12,
203,
3639,
2254,
5034,
1147,
734,
16,
203,
3639,
1758,
3082,
5541,
16,
203,
3639,
2254,
5034,
4993,
6518,
203,
565,
262,
3903,
1135,
261,
2867,
3082,
37,
2090,
16,
1758,
3082,
2090,
38,
1769,
203,
203,
565,
445,
527,
48,
18988,
24237,
12,
203,
3639,
1436,
48,
18988,
24237,
1370,
745,
892,
527,
1370,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
14096,
203,
565,
262,
3903,
1135,
261,
11890,
3844,
37,
16,
2254,
3844,
38,
16,
2254,
4501,
372,
24237,
37,
2090,
16,
2254,
4501,
372,
24237,
2090,
38,
1769,
203,
203,
565,
445,
527,
48,
18988,
24237,
1584,
44,
12,
203,
3639,
1436,
48,
18988,
24237,
1584,
44,
1370,
745,
892,
527,
1370,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
14096,
203,
565,
262,
3903,
8843,
429,
1135,
261,
11890,
3844,
1345,
16,
2254,
3844,
1584,
44,
16,
2254,
4501,
372,
24237,
56,
1448,
16,
2254,
4501,
372,
24237,
1448,
41,
1769,
203,
203,
565,
445,
1206,
48,
18988,
24237,
12,
203,
3639,
3581,
48,
18988,
24237,
1370,
745,
892,
1206,
1370,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
14096,
203,
565,
262,
3903,
1135,
261,
11890,
3844,
37,
16,
2254,
3844,
2
]
|
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.6.0;
import "@nomiclabs/buidler/console.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Obligation } from "./Obligation.sol";
import { IObligation } from "./interface/IObligation.sol";
import { IOption } from "./interface/IOption.sol";
import { European } from "./European.sol";
import { IReferee } from "./interface/IReferee.sol";
import { Bitcoin } from "./types/Bitcoin.sol";
/// @title Option ERC20
/// @author Interlay
/// @notice Represents options that may be exercised for the
/// backing currency in exchange for the underlying BTC.
contract Option is IOption, IERC20, European, Ownable {
using SafeMath for uint;
string constant ERR_TRANSFER_EXCEEDS_BALANCE = "Amount exceeds balance";
string constant ERR_APPROVE_TO_ZERO_ADDRESS = "Approve to zero address";
string constant ERR_TRANSFER_TO_ZERO_ADDRESS = "Transfer to zero address";
string constant ERR_APPROVE_FROM_ZERO_ADDRESS = "Approve from zero address";
string constant ERR_TRANSFER_FROM_ZERO_ADDRESS = "Transfer from zero address";
// event Insure(address indexed account, uint256 amount);
// event Exercise(address indexed account, uint256 amount);
// btc relay or oracle
address public override referee;
address public override treasury;
address public override obligation;
// account balances
mapping (address => uint256) internal _balances;
// accounts that can spend an owners funds
mapping (address => mapping (address => uint256)) internal _allowances;
// total number of options available
uint256 public override totalSupply;
constructor() public Ownable() {}
/**
* @notice Initializes the option-side contract with the
* expected parameters.
* @param _expiryTime Unix expiry date
* @param _windowSize Settlement window
* @param _referee Inclusion verifier
* @param _treasury Backing currency
* @param _obligation Obligation ERC20
**/
function initialize(
uint256 _expiryTime,
uint256 _windowSize,
address _referee,
address _treasury,
address _obligation
) external override onlyOwner {
require(_expiryTime > block.timestamp, ERR_INIT_EXPIRED);
require(_windowSize > 0, ERR_WINDOW_ZERO);
expiryTime = _expiryTime;
windowSize = _windowSize;
referee = _referee;
treasury = _treasury;
obligation = _obligation;
}
/**
* @notice Mints option tokens `from` a writer and transfers them `to` a
* participant - designed to immediately add liquidity to a pool. This contract
* will then call the owned Obligation contract to mint the `from` tokens. To
* prevent misappropriation of funds we expect this function to be called atomically
* after depositing in the treasury. The `OptionLib` contract should provide helpers
* to facilitate this.
* @dev Can only be called by the parent factory contract.
* @dev Once the expiry date has lapsed this function is no longer valid.
* @param from Origin address
* @param to Destination address (i.e. uniswap pool)
* @param amount Total credit
* @param btcHash Bitcoin hash
* @param format Bitcoin script format
**/
function mint(address from, address to, uint256 amount, bytes20 btcHash, Bitcoin.Script format) external override notExpired {
// collateral:(options/obligations) are 1:1
_balances[to] = _balances[to].add(amount);
totalSupply = totalSupply.add(amount);
emit Transfer(address(0), to, amount);
// mint the equivalent obligations
// obligation is responsible for locking with treasury
IObligation(obligation).mint(from, amount, btcHash, format);
}
function _burn(
address account,
uint256 amount
) internal {
_balances[account] = _balances[account].sub(amount);
totalSupply = totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function requestExercise(address seller, uint amount) external override canExercise {
// immediately burn options to prevent double spends
_burn(msg.sender, amount);
IObligation(obligation).requestExercise(msg.sender, seller, amount);
}
/**
* @notice Exercises an option after `expiryTime` but before `expiryTime + windowSize`.
* Requires a transaction inclusion proof which is verified by our chain relay.
* @dev Can only be called by the parent factory contract.
* @param seller Account to exercise against
* @param height Bitcoin block height
* @param index Bitcoin tx index
* @param txid Bitcoin transaction id
* @param proof Bitcoin inclusion proof
* @param rawtx Bitcoin raw tx
**/
function executeExercise(
address seller,
uint256 height,
uint256 index,
bytes32 txid,
bytes calldata proof,
bytes calldata rawtx
) external override canExercise {
address buyer = msg.sender;
(bytes20 btcHash,) = IObligation(obligation).getBtcAddress(seller);
// verify & validate tx, use default confirmations
uint output = IReferee(referee)
.verifyTx(
height,
index,
txid,
proof,
rawtx,
btcHash
);
// burn seller's obligations
IObligation(obligation).executeExercise(buyer, seller, output);
}
/**
* @notice Refund written collateral after `expiryTime + windowSize`.
* @dev Can only be called by the parent factory contract.
* @param amount Amount of collateral
**/
function refund(uint amount) external override canRefund {
// nothing to do here, forward
IObligation(obligation).refund(msg.sender, amount);
}
/// @dev See {IERC20-allowance}
function allowance(address owner, address spender) external override view returns (uint256) {
return _allowances[owner][spender];
}
/// @dev See {IERC20-approve}
function approve(address spender, uint256 amount) external override notExpired returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), ERR_APPROVE_FROM_ZERO_ADDRESS);
require(spender != address(0), ERR_APPROVE_TO_ZERO_ADDRESS);
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/// @dev See {IERC20-balanceOf}
function balanceOf(address account) external override view returns (uint256) {
return _balances[account];
}
/// @dev See {IERC20-transfer}
function transfer(address recipient, uint256 amount) external override notExpired returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/// @dev See {IERC20-transferFrom}
function transferFrom(address sender, address recipient, uint256 amount) external override notExpired returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, ERR_TRANSFER_EXCEEDS_BALANCE));
return true;
}
/**
* @dev Transfer the options from the sender to the recipient
* @param sender The address of the sender
* @param recipient The address of the recipient
* @param amount The amount of tokens to transfer
**/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal {
require(sender != address(0), ERR_TRANSFER_FROM_ZERO_ADDRESS);
require(recipient != address(0), ERR_TRANSFER_TO_ZERO_ADDRESS);
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
}
| * @notice Exercises an option after `expiryTime` but before `expiryTime + windowSize`. Requires a transaction inclusion proof which is verified by our chain relay. @dev Can only be called by the parent factory contract. @param seller Account to exercise against @param height Bitcoin block height @param index Bitcoin tx index @param txid Bitcoin transaction id @param proof Bitcoin inclusion proof @param rawtx Bitcoin raw tx/ verify & validate tx, use default confirmations burn seller's obligations | function executeExercise(
address seller,
uint256 height,
uint256 index,
bytes32 txid,
bytes calldata proof,
bytes calldata rawtx
) external override canExercise {
address buyer = msg.sender;
(bytes20 btcHash,) = IObligation(obligation).getBtcAddress(seller);
uint output = IReferee(referee)
.verifyTx(
height,
index,
txid,
proof,
rawtx,
btcHash
);
IObligation(obligation).executeExercise(buyer, seller, output);
}
| 2,518,354 | [
1,
424,
12610,
6141,
392,
1456,
1839,
1375,
22409,
950,
68,
1496,
1865,
1375,
22409,
950,
397,
27064,
8338,
16412,
279,
2492,
26485,
14601,
1492,
353,
13808,
635,
3134,
2687,
18874,
18,
225,
4480,
1338,
506,
2566,
635,
326,
982,
3272,
6835,
18,
225,
29804,
6590,
358,
24165,
5314,
225,
2072,
24420,
1203,
2072,
225,
770,
24420,
2229,
770,
225,
18372,
24420,
2492,
612,
225,
14601,
24420,
26485,
14601,
225,
1831,
978,
24420,
1831,
2229,
19,
3929,
473,
1954,
2229,
16,
999,
805,
6932,
1012,
18305,
29804,
1807,
320,
31627,
1012,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1836,
424,
20603,
12,
203,
3639,
1758,
29804,
16,
203,
3639,
2254,
5034,
2072,
16,
203,
3639,
2254,
5034,
770,
16,
203,
3639,
1731,
1578,
18372,
16,
203,
3639,
1731,
745,
892,
14601,
16,
203,
3639,
1731,
745,
892,
1831,
978,
203,
565,
262,
3903,
3849,
848,
424,
20603,
288,
203,
3639,
1758,
27037,
273,
1234,
18,
15330,
31,
203,
203,
3639,
261,
3890,
3462,
12798,
2310,
16,
13,
273,
1665,
31627,
367,
12,
947,
80,
360,
367,
2934,
588,
38,
5111,
1887,
12,
1786,
749,
1769,
203,
203,
3639,
2254,
876,
273,
467,
426,
586,
1340,
12,
266,
586,
1340,
13,
203,
5411,
263,
8705,
4188,
12,
203,
7734,
2072,
16,
203,
7734,
770,
16,
203,
7734,
18372,
16,
203,
7734,
14601,
16,
203,
7734,
1831,
978,
16,
203,
7734,
12798,
2310,
203,
5411,
11272,
203,
203,
3639,
1665,
31627,
367,
12,
947,
80,
360,
367,
2934,
8837,
424,
20603,
12,
70,
16213,
16,
29804,
16,
876,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/4/0x8CAb6E250CBE9129962a5Dc837d70c478d5C3af5/sources/FatMasterFarmer.sol | Withdraw LP tokens from FatMasterFarmer. | function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "FatMasterFarmer::withdraw: not good");
updatePool(_pid);
_harvest(_pid);
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accFatPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
| 8,563,365 | [
1,
1190,
9446,
511,
52,
2430,
628,
478,
270,
7786,
42,
4610,
264,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
598,
9446,
12,
11890,
5034,
389,
6610,
16,
2254,
5034,
389,
8949,
13,
1071,
288,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
3639,
25003,
2502,
729,
273,
16753,
63,
67,
6610,
6362,
3576,
18,
15330,
15533,
203,
3639,
2583,
12,
1355,
18,
8949,
1545,
389,
8949,
16,
315,
42,
270,
7786,
42,
4610,
264,
2866,
1918,
9446,
30,
486,
7494,
8863,
203,
203,
3639,
1089,
2864,
24899,
6610,
1769,
203,
3639,
389,
30250,
26923,
24899,
6610,
1769,
203,
203,
3639,
309,
24899,
8949,
405,
374,
13,
288,
203,
5411,
729,
18,
8949,
273,
729,
18,
8949,
18,
1717,
24899,
8949,
1769,
203,
5411,
2845,
18,
9953,
1345,
18,
4626,
5912,
12,
2867,
12,
3576,
18,
15330,
3631,
389,
8949,
1769,
203,
3639,
289,
203,
3639,
729,
18,
266,
2913,
758,
23602,
273,
729,
18,
8949,
18,
16411,
12,
6011,
18,
8981,
42,
270,
2173,
9535,
2934,
2892,
12,
21,
73,
2138,
1769,
203,
3639,
3626,
3423,
9446,
12,
3576,
18,
15330,
16,
389,
6610,
16,
389,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/3/0x7Ae043029345Daff53524bd9207A18133F0b178D/sources/faucet.sol | this faucet gives distributes money to different addresses that the owner chooses | contract FriendFaucet is Faucet{
struct user{
address user;
bool taxReceiver;
int256 index;
}
mapping (address=>user) receivesTax;
address[] userAddresses;
function addTaxReceiver(address _userAddress) public onlyOwner{
require(receivesTax[_userAddress].taxReceiver==false,"this address already receives tax");
receivesTax[_userAddress].taxReceiver=true;
}
function removeTaxReceiver(address _userAddress) public onlyOwner{
require(receivesTax[_userAddress].taxReceiver==true,"user was never receivving tax");
receivesTax[_userAddress].taxReceiver=false;
address replacingTaxReceiver=userAddresses[userAddresses.length-1];
userAddresses[uint256(receivesTax[_userAddress].index)]=userAddresses[userAddresses.length-1];
delete userAddresses[userAddresses.length-1];
receivesTax[replacingTaxReceiver].index=receivesTax[_userAddress].index;
receivesTax[_userAddress].index=-3;
}
function sendMoneyWithTax(uint256 withdraw_amount, address _userAddress) public enoughBalance(withdraw_amount){
}
}
| 8,174,909 | [
1,
2211,
11087,
5286,
278,
14758,
1015,
1141,
15601,
358,
3775,
6138,
716,
326,
3410,
24784,
281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
6835,
478,
7522,
29634,
5286,
278,
353,
478,
69,
5286,
278,
95,
203,
565,
1958,
729,
95,
203,
1377,
1758,
729,
31,
203,
1377,
1426,
5320,
12952,
31,
203,
1377,
509,
5034,
770,
31,
203,
565,
289,
203,
565,
2874,
261,
2867,
9207,
1355,
13,
17024,
7731,
31,
203,
565,
1758,
8526,
729,
7148,
31,
203,
565,
445,
527,
7731,
12952,
12,
2867,
389,
1355,
1887,
13,
1071,
1338,
5541,
95,
203,
1377,
2583,
12,
8606,
3606,
7731,
63,
67,
1355,
1887,
8009,
8066,
12952,
631,
5743,
10837,
2211,
1758,
1818,
17024,
5320,
8863,
203,
1377,
17024,
7731,
63,
67,
1355,
1887,
8009,
8066,
12952,
33,
3767,
31,
203,
565,
289,
203,
565,
445,
1206,
7731,
12952,
12,
2867,
389,
1355,
1887,
13,
1071,
1338,
5541,
95,
203,
1377,
2583,
12,
8606,
3606,
7731,
63,
67,
1355,
1887,
8009,
8066,
12952,
631,
3767,
10837,
1355,
1703,
5903,
2637,
427,
6282,
5320,
8863,
203,
1377,
17024,
7731,
63,
67,
1355,
1887,
8009,
8066,
12952,
33,
5743,
31,
203,
1377,
1758,
13993,
7731,
12952,
33,
1355,
7148,
63,
1355,
7148,
18,
2469,
17,
21,
15533,
203,
1377,
729,
7148,
63,
11890,
5034,
12,
8606,
3606,
7731,
63,
67,
1355,
1887,
8009,
1615,
25887,
33,
1355,
7148,
63,
1355,
7148,
18,
2469,
17,
21,
15533,
203,
1377,
1430,
729,
7148,
63,
1355,
7148,
18,
2469,
17,
21,
15533,
203,
1377,
17024,
7731,
63,
26745,
5330,
7731,
12952,
8009,
1615,
33,
8606,
3606,
7731,
63,
67,
1355,
1887,
8009,
1615,
31,
203,
1377,
17024,
7731,
63,
67,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/proxy/ClonesUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import "../interfaces/IGuild.sol";
/// @title GuildApp Proxy Factory
/// @author RaidGuild
/// @notice Allows to deploy a new GuildApp contract
/// @dev Based on EIP-1167
contract GuildFactory is Initializable {
using AddressUpgradeable for address;
using ClonesUpgradeable for address;
using CountersUpgradeable for CountersUpgradeable.Counter;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
/// @dev fixed contract template for EIP-1167 proxy pattern
address public template;
/// @dev keep track of total created Guilds
CountersUpgradeable.Counter private _totalGuilds;
/// @dev keep track of guild by owner
mapping(address => EnumerableSetUpgradeable.AddressSet) private _guilds;
/// @dev new guild event
event NewGuild(address indexed guildOwner, address indexed guild);
function __GuildFactory_init_unchained(address _template) internal initializer {
template = _template;
}
function __GuildFactory_init(address _template) internal initializer {
__GuildFactory_init_unchained(_template);
}
/// @notice Initializes the factory contract
/// @dev Initializes factory contract using a minimal proxy pattern (EIP-1167)
/// @param _template GuildApp contract address to be used as template
function initialize(address _template) public {
__GuildFactory_init(_template);
}
/// @notice get list of guilds created by `_owner`
/// @dev get GuildApp contract addresses created by `_owner`
/// @param _owner Guild app owner
/// @return an array of guilds created by `_owner`
function guildsOf(address _owner) public view returns (address[] memory) {
address[] memory tokens = new address[](_guilds[_owner].length());
for (uint256 i = 0; i < _guilds[_owner].length(); i++) {
tokens[i] = _guilds[_owner].at(i);
}
return tokens;
}
/// @notice get the total amount of existing guilds
/// @return total amount of deployed guilds
function totalGuilds() public view returns (uint256) {
return _totalGuilds.current();
}
/// @dev call GuildApp initialize function encoded in `_initData` and register the contract
/// @param _instance GuildApp contract address
/// @param _sender GuildApp owner
/// @param _initData Encoded GuildApp initialize function
function _initAndEmit(address _instance, address _sender, bytes calldata _initData) private {
_totalGuilds.increment();
emit NewGuild(_sender, _instance);
if (_initData.length > 0) {
_instance.functionCall(_initData);
}
IGuild guild = IGuild(_instance);
require(guild.initialized(), "GuildFactory: GuildApp not initialized");
_guilds[_sender].add(_instance);
}
/// @dev Clone the template using EIP-1167 and initlize the new deployment
/// @param _initData Encoded GuildApp initialize function
function clone(bytes calldata _initData) internal {
address sender = msg.sender;
_initAndEmit(template.clone(), sender, _initData);
}
/// @dev Clone the template using EIP-1167 + CREATE2 and initlize the new deployment
/// @param _initData Encoded GuildApp initialize function
/// @param _salt salt used for deploying the contract
function cloneDeterministic(bytes calldata _initData, bytes32 _salt) internal {
address sender = msg.sender;
_initAndEmit(template.cloneDeterministic(_salt), sender, _initData);
}
/// @notice Obtains the address that will be assigned to a new GuildApp contract
/// @dev
/// @param _salt salt used for deploying the contract
/// @return predicted contract address
function predictDeterministicAddress(bytes32 _salt) public view returns (address predicted) {
return template.predictDeterministicAddress(_salt);
}
/// @notice deploy a new GuildApp
/// @dev deploy a new GuildApp using the EIP-1167 Proxy pattern
/// @param _initData Encoded GuildApp initialize function
function createGuild(bytes calldata _initData) external {
require(template != address(0), "GuildFactory: Missing Guild Template");
clone(_initData);
}
// This is empty reserved space in storage that is put in place in Upgradeable contracts.
// It allows us to freely add new state variables in the future without compromising the
// storage compatibility with existing deployments
// The size of the __gap array is calculated so that the amount of storage used by a contract
// always adds up to the same number
uint256[47] private __gap;
} | @notice get list of guilds created by `_owner` @dev get GuildApp contract addresses created by `_owner` @param _owner Guild app owner @return an array of guilds created by `_owner` | function guildsOf(address _owner) public view returns (address[] memory) {
address[] memory tokens = new address[](_guilds[_owner].length());
for (uint256 i = 0; i < _guilds[_owner].length(); i++) {
tokens[i] = _guilds[_owner].at(i);
}
return tokens;
}
| 15,782,660 | [
1,
588,
666,
434,
15488,
87,
2522,
635,
1375,
67,
8443,
68,
225,
336,
24521,
3371,
6835,
6138,
2522,
635,
1375,
67,
8443,
68,
225,
389,
8443,
24521,
595,
3410,
327,
392,
526,
434,
15488,
87,
2522,
635,
1375,
67,
8443,
68,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
15488,
87,
951,
12,
2867,
389,
8443,
13,
1071,
1476,
1135,
261,
2867,
8526,
3778,
13,
288,
203,
3639,
1758,
8526,
3778,
2430,
273,
394,
1758,
8526,
24899,
75,
680,
87,
63,
67,
8443,
8009,
2469,
10663,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
389,
75,
680,
87,
63,
67,
8443,
8009,
2469,
5621,
277,
27245,
288,
203,
5411,
2430,
63,
77,
65,
273,
389,
75,
680,
87,
63,
67,
8443,
8009,
270,
12,
77,
1769,
203,
3639,
289,
203,
3639,
327,
2430,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.13;
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "../Bdx/BDXShares.sol";
import "./Vesting.sol";
import "./StakingRewards.sol";
contract StakingRewardsDistribution is OwnableUpgradeable {
using SafeERC20Upgradeable for BDXShares;
uint256 public TOTAL_BDX_SUPPLY;
uint256 public constant HUNDRED_PERCENT = 100;
uint256 public constant MAX_REWARD_FEE = 1e12;
// BDX minting schedule
// They sum up to 50% of TOTAL_BDX_SUPPLY
// as this much is reserved for liquidity mining rewards
uint256 public constant BDX_MINTING_SCHEDULE_PRECISON = 1000;
uint256 public BDX_MINTING_SCHEDULE_YEAR_1;
uint256 public BDX_MINTING_SCHEDULE_YEAR_2;
uint256 public BDX_MINTING_SCHEDULE_YEAR_3;
uint256 public BDX_MINTING_SCHEDULE_YEAR_4;
uint256 public BDX_MINTING_SCHEDULE_YEAR_5;
uint256 public EndOfYear_1;
uint256 public EndOfYear_2;
uint256 public EndOfYear_3;
uint256 public EndOfYear_4;
uint256 public EndOfYear_5;
uint256 public vestingRewardRatio_percent;
uint256 public rewardFee_d12;
BDXShares public rewardsToken;
Vesting public vesting;
address public treasury;
mapping(address => uint256) public stakingRewardsWeights;
address[] public stakingRewardsAddresses;
uint256 public stakingRewardsWeightsTotal;
function initialize(
address _rewardsToken,
address _vesting,
address _treasury,
uint256 _vestingRewardRatio_percent
) external initializer {
require(_rewardsToken != address(0), "Rewards address cannot be 0");
require(_vesting != address(0), "Vesting address cannot be 0");
require(_treasury != address(0), "Treasury address cannot be 0");
require(_vestingRewardRatio_percent <= 100, "VestingRewardRatio_percent must be <= 100");
__Ownable_init();
rewardsToken = BDXShares(_rewardsToken);
vesting = Vesting(_vesting);
treasury = _treasury;
TOTAL_BDX_SUPPLY = rewardsToken.MAX_TOTAL_SUPPLY();
BDX_MINTING_SCHEDULE_YEAR_1 = (TOTAL_BDX_SUPPLY * 200) / BDX_MINTING_SCHEDULE_PRECISON;
BDX_MINTING_SCHEDULE_YEAR_2 = (TOTAL_BDX_SUPPLY * 125) / BDX_MINTING_SCHEDULE_PRECISON;
BDX_MINTING_SCHEDULE_YEAR_3 = (TOTAL_BDX_SUPPLY * 100) / BDX_MINTING_SCHEDULE_PRECISON;
BDX_MINTING_SCHEDULE_YEAR_4 = (TOTAL_BDX_SUPPLY * 50) / BDX_MINTING_SCHEDULE_PRECISON;
BDX_MINTING_SCHEDULE_YEAR_5 = (TOTAL_BDX_SUPPLY * 25) / BDX_MINTING_SCHEDULE_PRECISON;
EndOfYear_1 = block.timestamp + 365 days;
EndOfYear_2 = block.timestamp + 2 * 365 days;
EndOfYear_3 = block.timestamp + 3 * 365 days;
EndOfYear_4 = block.timestamp + 4 * 365 days;
EndOfYear_5 = block.timestamp + 5 * 365 days;
vestingRewardRatio_percent = _vestingRewardRatio_percent;
rewardFee_d12 = 1e11; // 10%
}
// Precision 1e18 for compatibility with ERC20 token
function getRewardRatePerSecond(address _stakingRewardsAddress) external view returns (uint256) {
uint256 yearSchedule = 0;
if (block.timestamp < EndOfYear_1) {
yearSchedule = BDX_MINTING_SCHEDULE_YEAR_1;
} else if (block.timestamp < EndOfYear_2) {
yearSchedule = BDX_MINTING_SCHEDULE_YEAR_2;
} else if (block.timestamp < EndOfYear_3) {
yearSchedule = BDX_MINTING_SCHEDULE_YEAR_3;
} else if (block.timestamp < EndOfYear_4) {
yearSchedule = BDX_MINTING_SCHEDULE_YEAR_4;
} else if (block.timestamp < EndOfYear_5) {
yearSchedule = BDX_MINTING_SCHEDULE_YEAR_5;
} else {
yearSchedule = 0;
}
uint256 bdxPerSecond = (yearSchedule * stakingRewardsWeights[_stakingRewardsAddress]) / (365 * 24 * 60 * 60) / stakingRewardsWeightsTotal;
return bdxPerSecond;
}
function registerPools(address[] calldata _stakingRewardsAddresses, uint256[] calldata _stakingRewardsWeights) external onlyOwner {
require(_stakingRewardsAddresses.length == _stakingRewardsWeights.length, "Pools addresses and weights lengths should be the same");
for (uint256 i = 0; i < _stakingRewardsAddresses.length; i++) {
if (stakingRewardsWeights[_stakingRewardsAddresses[i]] == 0) {
// to avoid duplicates
stakingRewardsAddresses.push(_stakingRewardsAddresses[i]);
}
stakingRewardsWeightsTotal -= stakingRewardsWeights[_stakingRewardsAddresses[i]]; // to support override
stakingRewardsWeights[_stakingRewardsAddresses[i]] = _stakingRewardsWeights[i];
stakingRewardsWeightsTotal += _stakingRewardsWeights[i];
emit PoolRegistered(_stakingRewardsAddresses[i], _stakingRewardsWeights[i]);
}
}
function unregisterPool(
address pool,
uint256 from,
uint256 to
) external onlyOwner {
to = to < stakingRewardsAddresses.length ? to : stakingRewardsAddresses.length;
stakingRewardsWeightsTotal -= stakingRewardsWeights[pool];
stakingRewardsWeights[pool] = 0;
for (uint256 i = from; i < to; i++) {
if (stakingRewardsAddresses[i] == pool) {
stakingRewardsAddresses[i] = stakingRewardsAddresses[stakingRewardsAddresses.length - 1];
stakingRewardsAddresses.pop();
emit PoolRemoved(pool);
return;
}
}
}
function collectAllRewards(uint256 from, uint256 to) external {
to = to < stakingRewardsAddresses.length ? to : stakingRewardsAddresses.length;
uint256 totalFee;
uint256 totalRewardToRelease;
uint256 totalRewardToVest;
for (uint256 i = from; i < to; i++) {
StakingRewards stakingRewards = StakingRewards(stakingRewardsAddresses[i]);
stakingRewards.updateUserReward(msg.sender);
uint256 poolReward = stakingRewards.rewards(msg.sender);
if (poolReward > 0) {
uint256 rewardFee = (poolReward * rewardFee_d12) / MAX_REWARD_FEE;
uint256 userReward = poolReward - rewardFee;
uint256 immediatelyReleasedReward = calculateImmediateReward(userReward);
uint256 vestedReward = userReward - immediatelyReleasedReward;
totalFee = totalFee + rewardFee;
totalRewardToRelease = totalRewardToRelease + immediatelyReleasedReward;
totalRewardToVest = totalRewardToVest + vestedReward;
stakingRewards.releaseReward(msg.sender, immediatelyReleasedReward, vestedReward);
}
}
if (totalRewardToRelease > 0 || totalRewardToVest > 0) {
releaseReward(msg.sender, totalRewardToRelease, totalRewardToVest);
rewardsToken.safeTransfer(treasury, totalFee);
}
}
function setVestingRewardRatio(uint256 _vestingRewardRatio) external onlyOwner {
require(_vestingRewardRatio <= 100, "VestingRewardRatio_percent must be <= 100");
vestingRewardRatio_percent = _vestingRewardRatio;
emit VestingRewardRatioSet(_vestingRewardRatio);
}
function calculateImmediateReward(uint256 reward) private view returns (uint256) {
return (reward * (HUNDRED_PERCENT - vestingRewardRatio_percent)) / HUNDRED_PERCENT;
}
function releaseReward(
address to,
uint256 rewardToRelease,
uint256 rewardToVest
) private {
rewardsToken.approve(address(vesting), rewardToVest);
vesting.schedule(to, rewardToVest);
rewardsToken.safeTransfer(to, rewardToRelease);
}
function setTreasury(address _treasury) external onlyOwner {
treasury = _treasury;
emit TreasuryChanged(_treasury);
}
function setVesting(address _vesting) external onlyOwner {
vesting = Vesting(_vesting);
emit VestingChanged(_vesting);
}
function setRewardFee_d12(uint256 _rewardFee_d12) external onlyOwner {
require(_rewardFee_d12 <= MAX_REWARD_FEE, "Reward fee cannot exceed 100%");
rewardFee_d12 = _rewardFee_d12;
emit RewardFeeChanged(_rewardFee_d12);
}
modifier onlyStakingRewards() {
require(stakingRewardsWeights[msg.sender] > 0, "Only registered staking rewards contracts allowed");
_;
}
// ---------- EVENTS ----------
event PoolRemoved(address indexed pool);
event PoolRegistered(address indexed stakingRewardsAddress, uint256 indexed stakingRewardsWeight);
event VestingRewardRatioSet(uint256 vestingRewardRatio_percent);
event TreasuryChanged(address newTreasury);
event VestingChanged(address newVesting);
event RewardFeeChanged(uint256 newRewardFee_d12);
}
| BDX minting schedule They sum up to 50% of TOTAL_BDX_SUPPLY as this much is reserved for liquidity mining rewards | contract StakingRewardsDistribution is OwnableUpgradeable {
using SafeERC20Upgradeable for BDXShares;
uint256 public TOTAL_BDX_SUPPLY;
uint256 public constant HUNDRED_PERCENT = 100;
uint256 public constant MAX_REWARD_FEE = 1e12;
uint256 public constant BDX_MINTING_SCHEDULE_PRECISON = 1000;
uint256 public BDX_MINTING_SCHEDULE_YEAR_1;
uint256 public BDX_MINTING_SCHEDULE_YEAR_2;
uint256 public BDX_MINTING_SCHEDULE_YEAR_3;
uint256 public BDX_MINTING_SCHEDULE_YEAR_4;
uint256 public BDX_MINTING_SCHEDULE_YEAR_5;
uint256 public EndOfYear_1;
uint256 public EndOfYear_2;
uint256 public EndOfYear_3;
uint256 public EndOfYear_4;
uint256 public EndOfYear_5;
uint256 public vestingRewardRatio_percent;
uint256 public rewardFee_d12;
BDXShares public rewardsToken;
Vesting public vesting;
address public treasury;
mapping(address => uint256) public stakingRewardsWeights;
address[] public stakingRewardsAddresses;
uint256 public stakingRewardsWeightsTotal;
function initialize(
address _rewardsToken,
address _vesting,
address _treasury,
uint256 _vestingRewardRatio_percent
pragma solidity 0.8.13;
) external initializer {
require(_rewardsToken != address(0), "Rewards address cannot be 0");
require(_vesting != address(0), "Vesting address cannot be 0");
require(_treasury != address(0), "Treasury address cannot be 0");
require(_vestingRewardRatio_percent <= 100, "VestingRewardRatio_percent must be <= 100");
__Ownable_init();
rewardsToken = BDXShares(_rewardsToken);
vesting = Vesting(_vesting);
treasury = _treasury;
TOTAL_BDX_SUPPLY = rewardsToken.MAX_TOTAL_SUPPLY();
BDX_MINTING_SCHEDULE_YEAR_1 = (TOTAL_BDX_SUPPLY * 200) / BDX_MINTING_SCHEDULE_PRECISON;
BDX_MINTING_SCHEDULE_YEAR_2 = (TOTAL_BDX_SUPPLY * 125) / BDX_MINTING_SCHEDULE_PRECISON;
BDX_MINTING_SCHEDULE_YEAR_3 = (TOTAL_BDX_SUPPLY * 100) / BDX_MINTING_SCHEDULE_PRECISON;
BDX_MINTING_SCHEDULE_YEAR_4 = (TOTAL_BDX_SUPPLY * 50) / BDX_MINTING_SCHEDULE_PRECISON;
BDX_MINTING_SCHEDULE_YEAR_5 = (TOTAL_BDX_SUPPLY * 25) / BDX_MINTING_SCHEDULE_PRECISON;
EndOfYear_1 = block.timestamp + 365 days;
EndOfYear_2 = block.timestamp + 2 * 365 days;
EndOfYear_3 = block.timestamp + 3 * 365 days;
EndOfYear_4 = block.timestamp + 4 * 365 days;
EndOfYear_5 = block.timestamp + 5 * 365 days;
vestingRewardRatio_percent = _vestingRewardRatio_percent;
}
function getRewardRatePerSecond(address _stakingRewardsAddress) external view returns (uint256) {
uint256 yearSchedule = 0;
if (block.timestamp < EndOfYear_1) {
yearSchedule = BDX_MINTING_SCHEDULE_YEAR_1;
yearSchedule = BDX_MINTING_SCHEDULE_YEAR_2;
yearSchedule = BDX_MINTING_SCHEDULE_YEAR_3;
yearSchedule = BDX_MINTING_SCHEDULE_YEAR_4;
yearSchedule = BDX_MINTING_SCHEDULE_YEAR_5;
yearSchedule = 0;
}
uint256 bdxPerSecond = (yearSchedule * stakingRewardsWeights[_stakingRewardsAddress]) / (365 * 24 * 60 * 60) / stakingRewardsWeightsTotal;
return bdxPerSecond;
}
function getRewardRatePerSecond(address _stakingRewardsAddress) external view returns (uint256) {
uint256 yearSchedule = 0;
if (block.timestamp < EndOfYear_1) {
yearSchedule = BDX_MINTING_SCHEDULE_YEAR_1;
yearSchedule = BDX_MINTING_SCHEDULE_YEAR_2;
yearSchedule = BDX_MINTING_SCHEDULE_YEAR_3;
yearSchedule = BDX_MINTING_SCHEDULE_YEAR_4;
yearSchedule = BDX_MINTING_SCHEDULE_YEAR_5;
yearSchedule = 0;
}
uint256 bdxPerSecond = (yearSchedule * stakingRewardsWeights[_stakingRewardsAddress]) / (365 * 24 * 60 * 60) / stakingRewardsWeightsTotal;
return bdxPerSecond;
}
} else if (block.timestamp < EndOfYear_2) {
} else if (block.timestamp < EndOfYear_3) {
} else if (block.timestamp < EndOfYear_4) {
} else if (block.timestamp < EndOfYear_5) {
} else {
function registerPools(address[] calldata _stakingRewardsAddresses, uint256[] calldata _stakingRewardsWeights) external onlyOwner {
require(_stakingRewardsAddresses.length == _stakingRewardsWeights.length, "Pools addresses and weights lengths should be the same");
for (uint256 i = 0; i < _stakingRewardsAddresses.length; i++) {
if (stakingRewardsWeights[_stakingRewardsAddresses[i]] == 0) {
stakingRewardsAddresses.push(_stakingRewardsAddresses[i]);
}
stakingRewardsWeights[_stakingRewardsAddresses[i]] = _stakingRewardsWeights[i];
stakingRewardsWeightsTotal += _stakingRewardsWeights[i];
emit PoolRegistered(_stakingRewardsAddresses[i], _stakingRewardsWeights[i]);
}
}
function registerPools(address[] calldata _stakingRewardsAddresses, uint256[] calldata _stakingRewardsWeights) external onlyOwner {
require(_stakingRewardsAddresses.length == _stakingRewardsWeights.length, "Pools addresses and weights lengths should be the same");
for (uint256 i = 0; i < _stakingRewardsAddresses.length; i++) {
if (stakingRewardsWeights[_stakingRewardsAddresses[i]] == 0) {
stakingRewardsAddresses.push(_stakingRewardsAddresses[i]);
}
stakingRewardsWeights[_stakingRewardsAddresses[i]] = _stakingRewardsWeights[i];
stakingRewardsWeightsTotal += _stakingRewardsWeights[i];
emit PoolRegistered(_stakingRewardsAddresses[i], _stakingRewardsWeights[i]);
}
}
function registerPools(address[] calldata _stakingRewardsAddresses, uint256[] calldata _stakingRewardsWeights) external onlyOwner {
require(_stakingRewardsAddresses.length == _stakingRewardsWeights.length, "Pools addresses and weights lengths should be the same");
for (uint256 i = 0; i < _stakingRewardsAddresses.length; i++) {
if (stakingRewardsWeights[_stakingRewardsAddresses[i]] == 0) {
stakingRewardsAddresses.push(_stakingRewardsAddresses[i]);
}
stakingRewardsWeights[_stakingRewardsAddresses[i]] = _stakingRewardsWeights[i];
stakingRewardsWeightsTotal += _stakingRewardsWeights[i];
emit PoolRegistered(_stakingRewardsAddresses[i], _stakingRewardsWeights[i]);
}
}
function unregisterPool(
address pool,
uint256 from,
uint256 to
) external onlyOwner {
to = to < stakingRewardsAddresses.length ? to : stakingRewardsAddresses.length;
stakingRewardsWeightsTotal -= stakingRewardsWeights[pool];
stakingRewardsWeights[pool] = 0;
for (uint256 i = from; i < to; i++) {
if (stakingRewardsAddresses[i] == pool) {
stakingRewardsAddresses[i] = stakingRewardsAddresses[stakingRewardsAddresses.length - 1];
stakingRewardsAddresses.pop();
emit PoolRemoved(pool);
return;
}
}
}
function unregisterPool(
address pool,
uint256 from,
uint256 to
) external onlyOwner {
to = to < stakingRewardsAddresses.length ? to : stakingRewardsAddresses.length;
stakingRewardsWeightsTotal -= stakingRewardsWeights[pool];
stakingRewardsWeights[pool] = 0;
for (uint256 i = from; i < to; i++) {
if (stakingRewardsAddresses[i] == pool) {
stakingRewardsAddresses[i] = stakingRewardsAddresses[stakingRewardsAddresses.length - 1];
stakingRewardsAddresses.pop();
emit PoolRemoved(pool);
return;
}
}
}
function unregisterPool(
address pool,
uint256 from,
uint256 to
) external onlyOwner {
to = to < stakingRewardsAddresses.length ? to : stakingRewardsAddresses.length;
stakingRewardsWeightsTotal -= stakingRewardsWeights[pool];
stakingRewardsWeights[pool] = 0;
for (uint256 i = from; i < to; i++) {
if (stakingRewardsAddresses[i] == pool) {
stakingRewardsAddresses[i] = stakingRewardsAddresses[stakingRewardsAddresses.length - 1];
stakingRewardsAddresses.pop();
emit PoolRemoved(pool);
return;
}
}
}
function collectAllRewards(uint256 from, uint256 to) external {
to = to < stakingRewardsAddresses.length ? to : stakingRewardsAddresses.length;
uint256 totalFee;
uint256 totalRewardToRelease;
uint256 totalRewardToVest;
for (uint256 i = from; i < to; i++) {
StakingRewards stakingRewards = StakingRewards(stakingRewardsAddresses[i]);
stakingRewards.updateUserReward(msg.sender);
uint256 poolReward = stakingRewards.rewards(msg.sender);
if (poolReward > 0) {
uint256 rewardFee = (poolReward * rewardFee_d12) / MAX_REWARD_FEE;
uint256 userReward = poolReward - rewardFee;
uint256 immediatelyReleasedReward = calculateImmediateReward(userReward);
uint256 vestedReward = userReward - immediatelyReleasedReward;
totalFee = totalFee + rewardFee;
totalRewardToRelease = totalRewardToRelease + immediatelyReleasedReward;
totalRewardToVest = totalRewardToVest + vestedReward;
stakingRewards.releaseReward(msg.sender, immediatelyReleasedReward, vestedReward);
}
}
if (totalRewardToRelease > 0 || totalRewardToVest > 0) {
releaseReward(msg.sender, totalRewardToRelease, totalRewardToVest);
rewardsToken.safeTransfer(treasury, totalFee);
}
}
function collectAllRewards(uint256 from, uint256 to) external {
to = to < stakingRewardsAddresses.length ? to : stakingRewardsAddresses.length;
uint256 totalFee;
uint256 totalRewardToRelease;
uint256 totalRewardToVest;
for (uint256 i = from; i < to; i++) {
StakingRewards stakingRewards = StakingRewards(stakingRewardsAddresses[i]);
stakingRewards.updateUserReward(msg.sender);
uint256 poolReward = stakingRewards.rewards(msg.sender);
if (poolReward > 0) {
uint256 rewardFee = (poolReward * rewardFee_d12) / MAX_REWARD_FEE;
uint256 userReward = poolReward - rewardFee;
uint256 immediatelyReleasedReward = calculateImmediateReward(userReward);
uint256 vestedReward = userReward - immediatelyReleasedReward;
totalFee = totalFee + rewardFee;
totalRewardToRelease = totalRewardToRelease + immediatelyReleasedReward;
totalRewardToVest = totalRewardToVest + vestedReward;
stakingRewards.releaseReward(msg.sender, immediatelyReleasedReward, vestedReward);
}
}
if (totalRewardToRelease > 0 || totalRewardToVest > 0) {
releaseReward(msg.sender, totalRewardToRelease, totalRewardToVest);
rewardsToken.safeTransfer(treasury, totalFee);
}
}
function collectAllRewards(uint256 from, uint256 to) external {
to = to < stakingRewardsAddresses.length ? to : stakingRewardsAddresses.length;
uint256 totalFee;
uint256 totalRewardToRelease;
uint256 totalRewardToVest;
for (uint256 i = from; i < to; i++) {
StakingRewards stakingRewards = StakingRewards(stakingRewardsAddresses[i]);
stakingRewards.updateUserReward(msg.sender);
uint256 poolReward = stakingRewards.rewards(msg.sender);
if (poolReward > 0) {
uint256 rewardFee = (poolReward * rewardFee_d12) / MAX_REWARD_FEE;
uint256 userReward = poolReward - rewardFee;
uint256 immediatelyReleasedReward = calculateImmediateReward(userReward);
uint256 vestedReward = userReward - immediatelyReleasedReward;
totalFee = totalFee + rewardFee;
totalRewardToRelease = totalRewardToRelease + immediatelyReleasedReward;
totalRewardToVest = totalRewardToVest + vestedReward;
stakingRewards.releaseReward(msg.sender, immediatelyReleasedReward, vestedReward);
}
}
if (totalRewardToRelease > 0 || totalRewardToVest > 0) {
releaseReward(msg.sender, totalRewardToRelease, totalRewardToVest);
rewardsToken.safeTransfer(treasury, totalFee);
}
}
function collectAllRewards(uint256 from, uint256 to) external {
to = to < stakingRewardsAddresses.length ? to : stakingRewardsAddresses.length;
uint256 totalFee;
uint256 totalRewardToRelease;
uint256 totalRewardToVest;
for (uint256 i = from; i < to; i++) {
StakingRewards stakingRewards = StakingRewards(stakingRewardsAddresses[i]);
stakingRewards.updateUserReward(msg.sender);
uint256 poolReward = stakingRewards.rewards(msg.sender);
if (poolReward > 0) {
uint256 rewardFee = (poolReward * rewardFee_d12) / MAX_REWARD_FEE;
uint256 userReward = poolReward - rewardFee;
uint256 immediatelyReleasedReward = calculateImmediateReward(userReward);
uint256 vestedReward = userReward - immediatelyReleasedReward;
totalFee = totalFee + rewardFee;
totalRewardToRelease = totalRewardToRelease + immediatelyReleasedReward;
totalRewardToVest = totalRewardToVest + vestedReward;
stakingRewards.releaseReward(msg.sender, immediatelyReleasedReward, vestedReward);
}
}
if (totalRewardToRelease > 0 || totalRewardToVest > 0) {
releaseReward(msg.sender, totalRewardToRelease, totalRewardToVest);
rewardsToken.safeTransfer(treasury, totalFee);
}
}
function setVestingRewardRatio(uint256 _vestingRewardRatio) external onlyOwner {
require(_vestingRewardRatio <= 100, "VestingRewardRatio_percent must be <= 100");
vestingRewardRatio_percent = _vestingRewardRatio;
emit VestingRewardRatioSet(_vestingRewardRatio);
}
function calculateImmediateReward(uint256 reward) private view returns (uint256) {
return (reward * (HUNDRED_PERCENT - vestingRewardRatio_percent)) / HUNDRED_PERCENT;
}
function releaseReward(
address to,
uint256 rewardToRelease,
uint256 rewardToVest
) private {
rewardsToken.approve(address(vesting), rewardToVest);
vesting.schedule(to, rewardToVest);
rewardsToken.safeTransfer(to, rewardToRelease);
}
function setTreasury(address _treasury) external onlyOwner {
treasury = _treasury;
emit TreasuryChanged(_treasury);
}
function setVesting(address _vesting) external onlyOwner {
vesting = Vesting(_vesting);
emit VestingChanged(_vesting);
}
function setRewardFee_d12(uint256 _rewardFee_d12) external onlyOwner {
require(_rewardFee_d12 <= MAX_REWARD_FEE, "Reward fee cannot exceed 100%");
rewardFee_d12 = _rewardFee_d12;
emit RewardFeeChanged(_rewardFee_d12);
}
modifier onlyStakingRewards() {
require(stakingRewardsWeights[msg.sender] > 0, "Only registered staking rewards contracts allowed");
_;
}
event PoolRegistered(address indexed stakingRewardsAddress, uint256 indexed stakingRewardsWeight);
event VestingRewardRatioSet(uint256 vestingRewardRatio_percent);
event TreasuryChanged(address newTreasury);
event VestingChanged(address newVesting);
event RewardFeeChanged(uint256 newRewardFee_d12);
event PoolRemoved(address indexed pool);
}
| 2,575,786 | [
1,
18096,
60,
312,
474,
310,
4788,
16448,
2142,
731,
358,
6437,
9,
434,
399,
19851,
67,
18096,
60,
67,
13272,
23893,
282,
487,
333,
9816,
353,
8735,
364,
4501,
372,
24237,
1131,
310,
283,
6397,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
934,
6159,
17631,
14727,
9003,
353,
14223,
6914,
10784,
429,
288,
203,
565,
1450,
14060,
654,
39,
3462,
10784,
429,
364,
605,
28826,
24051,
31,
203,
203,
565,
2254,
5034,
1071,
399,
19851,
67,
18096,
60,
67,
13272,
23893,
31,
203,
203,
565,
2254,
5034,
1071,
5381,
670,
5240,
5879,
67,
3194,
19666,
273,
2130,
31,
203,
565,
2254,
5034,
1071,
5381,
4552,
67,
862,
21343,
67,
8090,
41,
273,
404,
73,
2138,
31,
203,
203,
565,
2254,
5034,
1071,
5381,
605,
28826,
67,
49,
3217,
1360,
67,
55,
27395,
67,
3670,
7266,
1413,
273,
4336,
31,
203,
565,
2254,
5034,
1071,
605,
28826,
67,
49,
3217,
1360,
67,
55,
27395,
67,
15137,
67,
21,
31,
203,
565,
2254,
5034,
1071,
605,
28826,
67,
49,
3217,
1360,
67,
55,
27395,
67,
15137,
67,
22,
31,
203,
565,
2254,
5034,
1071,
605,
28826,
67,
49,
3217,
1360,
67,
55,
27395,
67,
15137,
67,
23,
31,
203,
565,
2254,
5034,
1071,
605,
28826,
67,
49,
3217,
1360,
67,
55,
27395,
67,
15137,
67,
24,
31,
203,
565,
2254,
5034,
1071,
605,
28826,
67,
49,
3217,
1360,
67,
55,
27395,
67,
15137,
67,
25,
31,
203,
203,
565,
2254,
5034,
1071,
4403,
19091,
67,
21,
31,
203,
565,
2254,
5034,
1071,
4403,
19091,
67,
22,
31,
203,
565,
2254,
5034,
1071,
4403,
19091,
67,
23,
31,
203,
565,
2254,
5034,
1071,
4403,
19091,
67,
24,
31,
203,
565,
2254,
5034,
1071,
4403,
19091,
67,
25,
31,
203,
203,
565,
2254,
5034,
1071,
331,
10100,
17631,
1060,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '../Arth/IIncentive.sol';
/**
* @title A Uniswap Router for tokens involving ARTH.
* @author Original code written by FEI Protocol. Code modified by MahaDAO.
*/
interface IUniswapSwapRouter {
function buyARTHForETH(
uint256 minReward,
uint256 amountOutMin,
address to,
uint256 deadline
) external payable returns (uint256 amountOut);
function buyARTHForERC20(
address token,
uint256 amountIn,
uint256 minReward,
uint256 amountOutMin,
address to,
uint256 deadline
) external returns (uint256 amountOut);
function sellARTHForETH(
uint256 maxPenalty,
uint256 amountIn,
uint256 amountOutMin,
address to,
uint256 deadline
) external returns (uint256 amountOut);
function sellARTHForERC20(
address token,
uint256 maxPenalty,
uint256 amountIn,
uint256 amountOutMin,
address to,
uint256 deadline
) external returns (uint256 amountOut);
}
| * @title A Uniswap Router for tokens involving ARTH. @author Original code written by FEI Protocol. Code modified by MahaDAO./ | interface IUniswapSwapRouter {
function buyARTHForETH(
uint256 minReward,
uint256 amountOutMin,
address to,
uint256 deadline
) external payable returns (uint256 amountOut);
function buyARTHForERC20(
address token,
uint256 amountIn,
uint256 minReward,
uint256 amountOutMin,
address to,
uint256 deadline
) external returns (uint256 amountOut);
function sellARTHForETH(
uint256 maxPenalty,
uint256 amountIn,
uint256 amountOutMin,
address to,
uint256 deadline
) external returns (uint256 amountOut);
function sellARTHForERC20(
address token,
uint256 maxPenalty,
uint256 amountIn,
uint256 amountOutMin,
address to,
uint256 deadline
) external returns (uint256 amountOut);
}
| 5,418,608 | [
1,
37,
1351,
291,
91,
438,
9703,
364,
2430,
29876,
6282,
6052,
2455,
18,
225,
19225,
981,
5941,
635,
16439,
45,
4547,
18,
3356,
4358,
635,
490,
69,
3395,
18485,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5831,
467,
984,
291,
91,
438,
12521,
8259,
288,
203,
565,
445,
30143,
985,
2455,
1290,
1584,
44,
12,
203,
3639,
2254,
5034,
1131,
17631,
1060,
16,
203,
3639,
2254,
5034,
3844,
1182,
2930,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
14096,
203,
565,
262,
3903,
8843,
429,
1135,
261,
11890,
5034,
3844,
1182,
1769,
203,
203,
565,
445,
30143,
985,
2455,
1290,
654,
39,
3462,
12,
203,
3639,
1758,
1147,
16,
203,
3639,
2254,
5034,
3844,
382,
16,
203,
3639,
2254,
5034,
1131,
17631,
1060,
16,
203,
3639,
2254,
5034,
3844,
1182,
2930,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
14096,
203,
565,
262,
3903,
1135,
261,
11890,
5034,
3844,
1182,
1769,
203,
203,
565,
445,
357,
80,
985,
2455,
1290,
1584,
44,
12,
203,
3639,
2254,
5034,
943,
24251,
15006,
16,
203,
3639,
2254,
5034,
3844,
382,
16,
203,
3639,
2254,
5034,
3844,
1182,
2930,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
14096,
203,
565,
262,
3903,
1135,
261,
11890,
5034,
3844,
1182,
1769,
203,
203,
565,
445,
357,
80,
985,
2455,
1290,
654,
39,
3462,
12,
203,
3639,
1758,
1147,
16,
203,
3639,
2254,
5034,
943,
24251,
15006,
16,
203,
3639,
2254,
5034,
3844,
382,
16,
203,
3639,
2254,
5034,
3844,
1182,
2930,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
14096,
203,
565,
262,
3903,
1135,
261,
11890,
5034,
3844,
1182,
1769,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/43114/0x2711bC7c56f22650ac7ff99E0134b94C52455499/sources/unicryptBad.sol | but no date assigned
| if (dates[id_] == 0) { | 4,619,757 | [
1,
12885,
1158,
1509,
6958,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5411,
309,
261,
9683,
63,
350,
67,
65,
422,
374,
13,
288,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/84531/0x70bbB7a057A13070dF11d533e8f299357D778637/sources/project:/contracts/superfluid/SuperfluidToken.sol | NOTE: for future compatibility, these are reserved solidity slots The sub-class of SuperfluidToken solidity slot will start after _reserve13 | {
bytes32 private constant _REWARD_ADDRESS_CONFIG_KEY =
keccak256("org.superfluid-finance.superfluid.rewardAddress");
using SafeCast for uint256;
using SafeCast for int256;
ISuperfluid immutable internal _host;
mapping(address => uint256) internal _inactiveAgreementBitmap;
mapping(address => int256) internal _sharedSettledBalances;
uint256 internal _totalSupply;
uint256 internal _reserve4;
uint256 private _reserve5;
uint256 private _reserve6;
uint256 private _reserve7;
uint256 private _reserve8;
uint256 private _reserve9;
uint256 private _reserve10;
uint256 private _reserve11;
uint256 private _reserve12;
uint256 internal _reserve13;
constructor(
ISuperfluid host
pragma solidity 0.8.19;
import { ISuperfluid } from "../interfaces/superfluid/ISuperfluid.sol";
import { ISuperAgreement } from "../interfaces/superfluid/ISuperAgreement.sol";
import { ISuperfluidGovernance } from "../interfaces/superfluid/ISuperfluidGovernance.sol";
import { ISuperfluidToken } from "../interfaces/superfluid/ISuperfluidToken.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { EventsEmitter } from "../libs/EventsEmitter.sol";
import { FixedSizeData } from "../libs/FixedSizeData.sol";
abstract contract SuperfluidToken is ISuperfluidToken
) {
_host = host;
}
function getHost()
external view
override(ISuperfluidToken)
returns(address host)
{
return address(_host);
}
function realtimeBalanceOf(
address account,
uint256 timestamp
)
public view virtual override
returns (
int256 availableBalance,
uint256 deposit,
uint256 owedDeposit)
{
availableBalance = _sharedSettledBalances[account];
ISuperAgreement[] memory activeAgreements = getAccountActiveAgreements(account);
for (uint256 i = 0; i < activeAgreements.length; ++i) {
(
int256 agreementDynamicBalance,
uint256 agreementDeposit,
uint256 agreementOwedDeposit) = activeAgreements[i]
.realtimeBalanceOf(
this,
account,
timestamp
);
deposit = deposit + agreementDeposit;
owedDeposit = owedDeposit + agreementOwedDeposit;
availableBalance = availableBalance
+ agreementDynamicBalance
- (
agreementDeposit > agreementOwedDeposit ?
(agreementDeposit - agreementOwedDeposit) : 0
).toInt256();
}
}
function realtimeBalanceOf(
address account,
uint256 timestamp
)
public view virtual override
returns (
int256 availableBalance,
uint256 deposit,
uint256 owedDeposit)
{
availableBalance = _sharedSettledBalances[account];
ISuperAgreement[] memory activeAgreements = getAccountActiveAgreements(account);
for (uint256 i = 0; i < activeAgreements.length; ++i) {
(
int256 agreementDynamicBalance,
uint256 agreementDeposit,
uint256 agreementOwedDeposit) = activeAgreements[i]
.realtimeBalanceOf(
this,
account,
timestamp
);
deposit = deposit + agreementDeposit;
owedDeposit = owedDeposit + agreementOwedDeposit;
availableBalance = availableBalance
+ agreementDynamicBalance
- (
agreementDeposit > agreementOwedDeposit ?
(agreementDeposit - agreementOwedDeposit) : 0
).toInt256();
}
}
function realtimeBalanceOfNow(
address account
)
public view virtual override
returns (
int256 availableBalance,
uint256 deposit,
uint256 owedDeposit,
uint256 timestamp)
{
timestamp = _host.getNow();
(
availableBalance,
deposit,
owedDeposit
) = realtimeBalanceOf(account, timestamp);
}
function isAccountCritical(
address account,
uint256 timestamp
)
public view virtual override
returns(bool isCritical)
{
(int256 availableBalance,,) = realtimeBalanceOf(account, timestamp);
return availableBalance < 0;
}
function isAccountCriticalNow(
address account
)
external view virtual override
returns(bool isCritical)
{
return isAccountCritical(account, _host.getNow());
}
function isAccountSolvent(
address account,
uint256 timestamp
)
public view virtual override
returns(bool isSolvent)
{
(int256 availableBalance, uint256 deposit, uint256 owedDeposit) =
realtimeBalanceOf(account, timestamp);
int realtimeBalance = availableBalance
+ (deposit > owedDeposit ? (deposit - owedDeposit) : 0).toInt256();
return realtimeBalance >= 0;
}
function isAccountSolventNow(
address account
)
external view virtual override
returns(bool isSolvent)
{
return isAccountSolvent(account, _host.getNow());
}
function getAccountActiveAgreements(address account)
public view virtual override
returns(ISuperAgreement[] memory)
{
return _host.mapAgreementClasses(~_inactiveAgreementBitmap[account]);
}
function _mint(
address account,
uint256 amount
)
internal
{
_sharedSettledBalances[account] = _sharedSettledBalances[account] + amount.toInt256();
_totalSupply = _totalSupply + amount;
}
function _burn(
address account,
uint256 amount
)
internal
{
(int256 availableBalance,,) = realtimeBalanceOf(account, _host.getNow());
if (availableBalance < amount.toInt256()) {
revert SF_TOKEN_BURN_INSUFFICIENT_BALANCE();
}
_sharedSettledBalances[account] = _sharedSettledBalances[account] - amount.toInt256();
_totalSupply = _totalSupply - amount;
}
function _burn(
address account,
uint256 amount
)
internal
{
(int256 availableBalance,,) = realtimeBalanceOf(account, _host.getNow());
if (availableBalance < amount.toInt256()) {
revert SF_TOKEN_BURN_INSUFFICIENT_BALANCE();
}
_sharedSettledBalances[account] = _sharedSettledBalances[account] - amount.toInt256();
_totalSupply = _totalSupply - amount;
}
function _move(
address from,
address to,
int256 amount
)
internal
{
(int256 availableBalance,,) = realtimeBalanceOf(from, _host.getNow());
if (availableBalance < amount) {
revert SF_TOKEN_MOVE_INSUFFICIENT_BALANCE();
}
_sharedSettledBalances[from] = _sharedSettledBalances[from] - amount;
_sharedSettledBalances[to] = _sharedSettledBalances[to] + amount;
}
function _move(
address from,
address to,
int256 amount
)
internal
{
(int256 availableBalance,,) = realtimeBalanceOf(from, _host.getNow());
if (availableBalance < amount) {
revert SF_TOKEN_MOVE_INSUFFICIENT_BALANCE();
}
_sharedSettledBalances[from] = _sharedSettledBalances[from] - amount;
_sharedSettledBalances[to] = _sharedSettledBalances[to] + amount;
}
function _getRewardAccount() internal view returns (address rewardAccount) {
ISuperfluidGovernance gov = _host.getGovernance();
rewardAccount = gov.getConfigAsAddress(_host, this, _REWARD_ADDRESS_CONFIG_KEY);
}
function createAgreement(
bytes32 id,
bytes32[] calldata data
)
external virtual override
{
address agreementClass = msg.sender;
bytes32 slot = keccak256(abi.encode("AgreementData", agreementClass, id));
if (FixedSizeData.hasData(slot, data.length)) {
revert SF_TOKEN_AGREEMENT_ALREADY_EXISTS();
}
FixedSizeData.storeData(slot, data);
emit AgreementCreated(agreementClass, id, data);
}
function createAgreement(
bytes32 id,
bytes32[] calldata data
)
external virtual override
{
address agreementClass = msg.sender;
bytes32 slot = keccak256(abi.encode("AgreementData", agreementClass, id));
if (FixedSizeData.hasData(slot, data.length)) {
revert SF_TOKEN_AGREEMENT_ALREADY_EXISTS();
}
FixedSizeData.storeData(slot, data);
emit AgreementCreated(agreementClass, id, data);
}
function getAgreementData(
address agreementClass,
bytes32 id,
uint dataLength
)
external view virtual override
returns(bytes32[] memory data)
{
bytes32 slot = keccak256(abi.encode("AgreementData", agreementClass, id));
data = FixedSizeData.loadData(slot, dataLength);
}
function updateAgreementData(
bytes32 id,
bytes32[] calldata data
)
external virtual override
{
address agreementClass = msg.sender;
bytes32 slot = keccak256(abi.encode("AgreementData", agreementClass, id));
FixedSizeData.storeData(slot, data);
emit AgreementUpdated(msg.sender, id, data);
}
function terminateAgreement(
bytes32 id,
uint dataLength
)
external virtual override
{
address agreementClass = msg.sender;
bytes32 slot = keccak256(abi.encode("AgreementData", agreementClass, id));
if (!FixedSizeData.hasData(slot,dataLength)) {
revert SF_TOKEN_AGREEMENT_DOES_NOT_EXIST();
}
FixedSizeData.eraseData(slot, dataLength);
emit AgreementTerminated(msg.sender, id);
}
function terminateAgreement(
bytes32 id,
uint dataLength
)
external virtual override
{
address agreementClass = msg.sender;
bytes32 slot = keccak256(abi.encode("AgreementData", agreementClass, id));
if (!FixedSizeData.hasData(slot,dataLength)) {
revert SF_TOKEN_AGREEMENT_DOES_NOT_EXIST();
}
FixedSizeData.eraseData(slot, dataLength);
emit AgreementTerminated(msg.sender, id);
}
function updateAgreementStateSlot(
address account,
uint256 slotId,
bytes32[] calldata slotData
)
external virtual override
{
bytes32 slot = keccak256(abi.encode("AgreementState", msg.sender, account, slotId));
FixedSizeData.storeData(slot, slotData);
emit AgreementStateUpdated(msg.sender, account, slotId);
}
function getAgreementStateSlot(
address agreementClass,
address account,
uint256 slotId,
uint dataLength
)
external view virtual override
returns (bytes32[] memory slotData) {
bytes32 slot = keccak256(abi.encode("AgreementState", agreementClass, account, slotId));
slotData = FixedSizeData.loadData(slot, dataLength);
}
function settleBalance(
address account,
int256 delta
)
external virtual override
onlyAgreement
{
_sharedSettledBalances[account] = _sharedSettledBalances[account] + delta;
}
function makeLiquidationPayoutsV2(
bytes32 id,
bytes memory liquidationTypeData,
) external virtual override onlyAgreement {
address rewardAccount = _getRewardAccount();
if (rewardAccount == address(0)) {
rewardAccount = liquidatorAccount;
}
address rewardAmountReceiver = useDefaultRewardAccount ? rewardAccount : liquidatorAccount;
if (targetAccountBalanceDelta <= 0) {
assert(rewardAmount.toInt256() == -targetAccountBalanceDelta);
_sharedSettledBalances[rewardAmountReceiver] += rewardAmount.toInt256();
_sharedSettledBalances[targetAccount] += targetAccountBalanceDelta;
EventsEmitter.emitTransfer(targetAccount, rewardAmountReceiver, rewardAmount);
assert(!useDefaultRewardAccount);
_sharedSettledBalances[rewardAccount] -= (rewardAmount.toInt256() + targetAccountBalanceDelta);
_sharedSettledBalances[liquidatorAccount] += rewardAmount.toInt256();
_sharedSettledBalances[targetAccount] += targetAccountBalanceDelta;
EventsEmitter.emitTransfer(rewardAccount, liquidatorAccount, rewardAmount);
EventsEmitter.emitTransfer(rewardAccount, targetAccount, uint256(targetAccountBalanceDelta));
}
emit AgreementLiquidatedV2(
msg.sender,
id,
liquidatorAccount,
targetAccount,
rewardAmountReceiver,
rewardAmount,
targetAccountBalanceDelta,
liquidationTypeData
);
}
function makeLiquidationPayoutsV2(
bytes32 id,
bytes memory liquidationTypeData,
) external virtual override onlyAgreement {
address rewardAccount = _getRewardAccount();
if (rewardAccount == address(0)) {
rewardAccount = liquidatorAccount;
}
address rewardAmountReceiver = useDefaultRewardAccount ? rewardAccount : liquidatorAccount;
if (targetAccountBalanceDelta <= 0) {
assert(rewardAmount.toInt256() == -targetAccountBalanceDelta);
_sharedSettledBalances[rewardAmountReceiver] += rewardAmount.toInt256();
_sharedSettledBalances[targetAccount] += targetAccountBalanceDelta;
EventsEmitter.emitTransfer(targetAccount, rewardAmountReceiver, rewardAmount);
assert(!useDefaultRewardAccount);
_sharedSettledBalances[rewardAccount] -= (rewardAmount.toInt256() + targetAccountBalanceDelta);
_sharedSettledBalances[liquidatorAccount] += rewardAmount.toInt256();
_sharedSettledBalances[targetAccount] += targetAccountBalanceDelta;
EventsEmitter.emitTransfer(rewardAccount, liquidatorAccount, rewardAmount);
EventsEmitter.emitTransfer(rewardAccount, targetAccount, uint256(targetAccountBalanceDelta));
}
emit AgreementLiquidatedV2(
msg.sender,
id,
liquidatorAccount,
targetAccount,
rewardAmountReceiver,
rewardAmount,
targetAccountBalanceDelta,
liquidationTypeData
);
}
function makeLiquidationPayoutsV2(
bytes32 id,
bytes memory liquidationTypeData,
) external virtual override onlyAgreement {
address rewardAccount = _getRewardAccount();
if (rewardAccount == address(0)) {
rewardAccount = liquidatorAccount;
}
address rewardAmountReceiver = useDefaultRewardAccount ? rewardAccount : liquidatorAccount;
if (targetAccountBalanceDelta <= 0) {
assert(rewardAmount.toInt256() == -targetAccountBalanceDelta);
_sharedSettledBalances[rewardAmountReceiver] += rewardAmount.toInt256();
_sharedSettledBalances[targetAccount] += targetAccountBalanceDelta;
EventsEmitter.emitTransfer(targetAccount, rewardAmountReceiver, rewardAmount);
assert(!useDefaultRewardAccount);
_sharedSettledBalances[rewardAccount] -= (rewardAmount.toInt256() + targetAccountBalanceDelta);
_sharedSettledBalances[liquidatorAccount] += rewardAmount.toInt256();
_sharedSettledBalances[targetAccount] += targetAccountBalanceDelta;
EventsEmitter.emitTransfer(rewardAccount, liquidatorAccount, rewardAmount);
EventsEmitter.emitTransfer(rewardAccount, targetAccount, uint256(targetAccountBalanceDelta));
}
emit AgreementLiquidatedV2(
msg.sender,
id,
liquidatorAccount,
targetAccount,
rewardAmountReceiver,
rewardAmount,
targetAccountBalanceDelta,
liquidationTypeData
);
}
} else {
modifier onlyAgreement() {
if (!_host.isAgreementClassListed(ISuperAgreement(msg.sender))) {
revert SF_TOKEN_ONLY_LISTED_AGREEMENT();
}
_;
}
modifier onlyAgreement() {
if (!_host.isAgreementClassListed(ISuperAgreement(msg.sender))) {
revert SF_TOKEN_ONLY_LISTED_AGREEMENT();
}
_;
}
modifier onlyHost() {
if (address(_host) != msg.sender) {
revert SF_TOKEN_ONLY_HOST();
}
_;
}
modifier onlyHost() {
if (address(_host) != msg.sender) {
revert SF_TOKEN_ONLY_HOST();
}
_;
}
}
| 11,527,354 | [
1,
17857,
30,
364,
3563,
8926,
16,
4259,
854,
8735,
18035,
560,
12169,
1021,
720,
17,
1106,
434,
14845,
2242,
1911,
1345,
18035,
560,
4694,
903,
787,
1839,
389,
455,
6527,
3437,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
95,
203,
203,
565,
1731,
1578,
3238,
5381,
389,
862,
21343,
67,
15140,
67,
7203,
67,
3297,
273,
203,
3639,
417,
24410,
581,
5034,
2932,
3341,
18,
9565,
2242,
1911,
17,
926,
1359,
18,
9565,
2242,
1911,
18,
266,
2913,
1887,
8863,
203,
203,
565,
1450,
14060,
9735,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
9735,
364,
509,
5034,
31,
203,
203,
565,
467,
8051,
2242,
1911,
11732,
2713,
389,
2564,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
2713,
389,
27366,
17420,
12224,
31,
203,
203,
565,
2874,
12,
2867,
516,
509,
5034,
13,
2713,
389,
11574,
694,
88,
1259,
38,
26488,
31,
203,
203,
565,
2254,
5034,
2713,
389,
4963,
3088,
1283,
31,
203,
203,
565,
2254,
5034,
2713,
389,
455,
6527,
24,
31,
203,
565,
2254,
5034,
3238,
389,
455,
6527,
25,
31,
203,
565,
2254,
5034,
3238,
389,
455,
6527,
26,
31,
203,
565,
2254,
5034,
3238,
389,
455,
6527,
27,
31,
203,
565,
2254,
5034,
3238,
389,
455,
6527,
28,
31,
203,
565,
2254,
5034,
3238,
389,
455,
6527,
29,
31,
203,
565,
2254,
5034,
3238,
389,
455,
6527,
2163,
31,
203,
565,
2254,
5034,
3238,
389,
455,
6527,
2499,
31,
203,
565,
2254,
5034,
3238,
389,
455,
6527,
2138,
31,
203,
565,
2254,
5034,
2713,
389,
455,
6527,
3437,
31,
203,
203,
565,
3885,
12,
203,
3639,
467,
8051,
2242,
1911,
1479,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
3657,
31,
203,
5666,
288,
467,
8051,
2242,
1911,
289,
628,
315,
6216,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
// Openzeppelin.
import "./openzeppelin-solidity/contracts/SafeMath.sol";
import "./openzeppelin-solidity/contracts/Ownable.sol";
import "./openzeppelin-solidity/contracts/ReentrancyGuard.sol";
import "./openzeppelin-solidity/contracts/ERC20/SafeERC20.sol";
// Internal references.
import './interfaces/IKeeper.sol';
import './interfaces/IComponentsRegistry.sol';
import './interfaces/ITradingBotRegistry.sol';
import './interfaces/IIndicator.sol';
import './interfaces/IComparator.sol';
import './interfaces/ITradingBot.sol';
import './interfaces/IKeeperFactory.sol';
// Inheritance.
import './interfaces/IKeeperRegistry.sol';
contract KeeperRegistry is IKeeperRegistry, Ownable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 constant MAX_JOBS_PER_KEEPER = 10;
uint256 MAX_KEEPER_FEE;
uint256 MAX_FEE_INCREASE;
uint256 constant MIN_TIME_BETWEEN_FEE_CHANGES = 1 days;
IERC20 immutable feeToken;
IComponentsRegistry immutable componentsRegistry;
ITradingBotRegistry immutable tradingBotRegistry;
IKeeperFactory immutable keeperFactory;
// (job ID => job info).
mapping (uint256 => Upkeep) public upkeeps;
// (keeper contract address => keeper info).
mapping (address => KeeperInfo) public keepers;
// (job ID => available funds).
// Funds are deducted from a job whenever a keeper performs upkeep on the job.
mapping (uint256 => uint256) public override availableFunds;
// (payee => uncollected fees).
// Fees are added to a payee whenever the keeper associated with the payee performs upkeep on a job.
mapping (address => uint256) public override availableFees;
// (user address => address of deployed keeper contract).
// Limit of 1 deployed keeper contract per user.
mapping (address => address) public userToKeeper;
// (keeper contract address => array of job IDs the keeper is responsible for).
mapping (address => uint256[]) public keeperJobs;
// (keeper contract address => timestamp).
mapping (address => uint256) public lastFeeChange;
// Total number of jobs that have been created.
// When a job is created, the job's ID is [numberOfJobs] at the time.
// This ensures job IDs are strictly increasing.
uint256 public numberOfJobs;
constructor(address _feeToken, address _componentsRegistry, address _tradingBotRegistry, address _keeperFactory) Ownable() {
feeToken = IERC20(_feeToken);
componentsRegistry = IComponentsRegistry(_componentsRegistry);
tradingBotRegistry = ITradingBotRegistry(_tradingBotRegistry);
keeperFactory = IKeeperFactory(_keeperFactory);
MAX_FEE_INCREASE = 1e20;
MAX_KEEPER_FEE = 1e21;
}
/* ========== VIEWS ========== */
/**
* @notice Returns the upkeep info for the given job ID.
* @dev Instance ID is not used if the target contract is a trading bot.
* @dev Returns 0 for each value if the job ID is not valid.
* @param _jobID The ID of the job.
* @return (bool, uint8, address, address, address, uint256) Whether the job is active, the job type, the job's owner, the job's keeper, the target contract address, and the instance ID.
*/
function getUpkeepInfo(uint256 _jobID) external view override returns (bool, uint8, address, address, address, uint256) {
// Gas savings.
Upkeep memory upkeep = upkeeps[_jobID];
return (upkeep.isActive, upkeep.jobType, upkeep.owner, upkeep.keeper, upkeep.target, upkeep.instanceID);
}
/**
* @notice Returns the keeper info for the given keeper contract.
* @param _keeper Address of the keeper.
* @return (address, address, address, uint256, uint256[]) Address of the keeper contract's owner, address of the keeper's dedicated caller, address of the keeper fee recipient, fee per upkeep, and an array of job IDs.
*/
function getKeeperInfo(address _keeper) external view override returns (address, address, address, uint256, uint256[] memory) {
// Gas savings.
KeeperInfo memory keeper = keepers[_keeper];
uint256[] memory jobs = new uint256[](keeperJobs[_keeper].length);
for (uint256 i = 0; i < jobs.length; i++) {
jobs[i] = keeperJobs[_keeper][i];
}
return (keeper.owner, keeper.caller, keeper.payee, keeper.fee, jobs);
}
/**
* @notice Returns whether the given job has enough funds to pay the keeper fee.
*/
function checkBudget(uint256 _jobID) external view override returns (bool) {
address keeper = upkeeps[_jobID].keeper;
uint256 fee = keepers[keeper].fee;
return availableFunds[_jobID] >= fee;
}
/**
* @notice Returns the address of the given job's keeper contract.
*/
function getJobKeeper(uint256 _jobID) external view override returns (address) {
return upkeeps[_jobID].keeper;
}
/**
* @notice Returns ID of each job the given keeper is responsible for.
* @dev Returns an empty array if the keeper is not registered or doesn't have any jobs.
*/
function getAvailableJobs(address _keeper) external view override returns (uint256[] memory) {
uint256[] memory jobs = new uint256[](keeperJobs[_keeper].length);
for (uint256 i = 0; i < jobs.length; i++) {
jobs[i] = keeperJobs[_keeper][i];
}
return jobs;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Adds funds to the given job.
* @dev Only the job's owner can call this function.
* @param _jobID The ID of the job.
* @param _amount Number of tokens to transfer.
*/
function addFunds(uint256 _jobID, uint256 _amount) external override onlyJobOwner(_jobID) nonReentrant {
availableFunds[_jobID] = availableFunds[_jobID].add(_amount);
feeToken.safeTransferFrom(msg.sender, address(this), _amount);
emit AddedFunds(_jobID, msg.sender, _amount);
}
/**
* @notice Withdraws funds from the given job.
* @dev Only the job's owner can call this function.
* @param _jobID The ID of the job.
* @param _amount Number of tokens to withdraw.
*/
function withdrawFunds(uint256 _jobID, uint256 _amount) external override onlyJobOwner(_jobID) nonReentrant {
_withdrawFunds(msg.sender, _jobID, _amount);
}
/**
* @notice Registers a new keeper to the platform.
* @dev This function deploys a new Keeper contract.
* @dev This function can only be called once per user.
* @param _caller Address of the Keeper contract's dedicated caller.
* @param _payee Address of the user/contract that can claim keeper fees.
* @param _fee Fee to charge whenever an upkeep is performed.
*/
function registerKeeper(address _caller, address _payee, uint256 _fee) external override {
require(userToKeeper[msg.sender] == address(0), "KeeperRegistry: Already have a keeper contract.");
require(_caller != address(0), "KeeperRegistry: Invalid address for _caller.");
require(_payee != address(0), "KeeperRegistry: Invalid address for _payee.");
require(_fee <= MAX_KEEPER_FEE, "KeeperRegistry: Keeper fee is too high.");
// Create a Keeper contract.
address keeperAddress = keeperFactory.createKeeper(msg.sender, _caller);
userToKeeper[msg.sender] = keeperAddress;
keepers[keeperAddress] = KeeperInfo({
owner: msg.sender,
caller: _caller,
payee: _payee,
fee: _fee
});
emit RegisteredKeeper(keeperAddress, msg.sender, _caller, _payee, _fee);
}
/**
* @notice Updates the fee recipient for the given keeper contract.
* @dev This function can only be called by the keeper contract's owner.
* @param _keeper Address of the keeper contract.
* @param _newPayee Address of the new fee recipient.
*/
function updatePayee(address _keeper, address _newPayee) external override onlyKeeperOwner(_keeper) {
keepers[_keeper].payee = _newPayee;
emit UpdatedPayee(_keeper, _newPayee);
}
/**
* @notice Claims all available fees for the given keeper contract.
* @dev Assumes that msg.sender is the payee.
* @dev Only the keeper contract's payee can call this function.
* @param _keeper Address of the keeper contract.
*/
function claimFees(address _keeper) external override onlyPayee(_keeper) nonReentrant {
uint256 amount = availableFees[msg.sender];
availableFees[msg.sender] = 0;
feeToken.safeTransfer(msg.sender, amount);
emit ClaimedFees(_keeper, msg.sender, amount);
}
/**
* @notice Creates a new job.
* @dev Only the owner of the indicator/comaprator/bot can call this function.
* @param _jobType The job type; 0 = indicator, 1 = comparator, 2 = trading bot.
* @param _keeper Address of the keeper contract.
* @param _target Address of the indicator/comparator/bot contract.
* @param _instanceID Instance ID of the indicator/comparator.
*/
function createJob(uint8 _jobType, address _keeper, address _target, uint256 _instanceID) external override {
require(_jobType >= 0 && _jobType <= 2, "KeeperRegistry: Invalid job type.");
require(keepers[_keeper].owner != address(0), "KeeperRegistry: Invalid keeper.");
require(keeperJobs[_keeper].length <= MAX_JOBS_PER_KEEPER, "KeeperRegistry: Keeper does not have room for another job.");
// Check if target is valid indicator/comparator/bot.
// Check if msg.sender owns the instance ID.
// Check that there's no existing keeper for the target/instance.
if (_jobType == 0 || _jobType == 1) {
require(componentsRegistry.checkInfoForUpkeep(msg.sender, _jobType == 0, _target, _instanceID), "KeeperRegistry: Invalid info for upkeep.");
if (_jobType == 0) {
IIndicator(_target).setKeeper(_instanceID, _keeper);
}
else {
IComparator(_target).setKeeper(_instanceID, _keeper);
}
}
else {
require(tradingBotRegistry.checkInfoForUpkeep(msg.sender, _target), "KeeperRegistry: Invalid info for upkeep.");
ITradingBot(_target).setKeeper(_keeper);
}
uint256 jobID = numberOfJobs.add(1);
numberOfJobs = jobID;
keeperJobs[_keeper].push(jobID);
upkeeps[jobID] = Upkeep({
isActive: true,
jobType: _jobType,
owner: msg.sender,
keeper: _keeper,
target: _target,
instanceID: _instanceID
});
emit CreatedJob(_jobType, jobID, msg.sender, _keeper, _target, _instanceID);
}
/**
* @notice Cancels a job.
* @dev Only the job's owner can call this function.
* @dev Any outstanding funds for the job are returned to the job's owner.
* @param _jobID The job ID.
*/
function cancelJob(uint256 _jobID) external override onlyJobOwner(_jobID) {
upkeeps[_jobID].isActive = false;
upkeeps[_jobID].owner = address(0);
// Find the index of the job ID in the keeper's array of jobs.
uint256 index;
address keeper = upkeeps[_jobID].keeper;
uint256 length = keeperJobs[keeper].length;
for (; index < length; index++) {
if (keeperJobs[keeper][index] == _jobID) {
break;
}
}
require(index < length, "KeeperRegistry: Job not found.");
// Move the job ID at the last index to the index of the job being cancelled.
keeperJobs[keeper][index] = keeperJobs[keeper][length.sub(1)];
keeperJobs[keeper].pop();
uint256 jobType = upkeeps[_jobID].jobType;
address target = upkeeps[_jobID].target;
uint256 instanceID = upkeeps[_jobID].instanceID;
if (jobType == 0) {
IIndicator(target).setKeeper(instanceID, address(0));
}
else if (jobType == 1) {
IComparator(target).setKeeper(instanceID, address(0));
}
else if (jobType == 2) {
ITradingBot(target).setKeeper(address(0));
}
_withdrawFunds(msg.sender, _jobID, availableFunds[_jobID]);
emit CanceledJob(_jobID);
}
/**
* @notice Updates the keeper's fee.
* @dev Only the keeper contract's owner can call this function.
* @param _keeper Address of the keeper contract.
* @param _newFee The new keeper fee.
*/
function updateKeeperFee(address _keeper, uint256 _newFee) external override onlyKeeperOwner(_keeper) {
require(_newFee <= MAX_KEEPER_FEE, "KeeperRegistry: New fee is too high.");
require(block.timestamp.sub(lastFeeChange[_keeper]) >= MIN_TIME_BETWEEN_FEE_CHANGES, "KeeperRegistry: Not enough time between fee changes.");
// Enforce MAX_FEE_INCREASE if the new fee is higher than the current fee.
if (_newFee > keepers[_keeper].fee) {
require(_newFee.sub(keepers[_keeper].fee) <= MAX_FEE_INCREASE, "KeeperRegistry: Fee increase is too high.");
}
keepers[_keeper].fee = _newFee;
lastFeeChange[_keeper] = block.timestamp;
emit UpdatedKeeperFee(_keeper, _newFee);
}
/**
* @notice Charges the keeper fee for the given job.
* @dev Only a keeper contract can call this function (assumes msg.sender is a keeper contract).
* @dev Transaction will revert if the keeper is not responsible for the given job.
* @param _jobID The job ID.
*/
function chargeFee(uint256 _jobID) external override onlyKeeper(_jobID) nonReentrant {
address keeper = upkeeps[_jobID].keeper;
address payee = keepers[keeper].payee;
uint256 fee = keepers[keeper].fee;
availableFunds[_jobID] = availableFunds[_jobID].sub(fee);
availableFees[payee] = availableFees[payee].add(fee);
emit ChargedFee(_jobID, payee, fee);
}
/**
* @notice Updates the address of the given keeper contract's dedicated caller.
* @dev Only the keeper contract's owner can call this function.
* @param _keeper Address of the keeper contract.
* @param _newCaller Address of the new dedicated caller.
*/
function updateDedicatedCaller(address _keeper, address _newCaller) external override onlyKeeperOwner(_keeper) {
require(_newCaller != address(0), "KeeperRegistry: Invalid address for _newCaller.");
keepers[_keeper].caller = _newCaller;
IKeeper(_keeper).updateDedicatedCaller(_newCaller);
emit UpdatedDedicatedCaller(_keeper, _newCaller);
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice Updates the max keeper fee.
* @dev Only the KeeperRegistry's owner can call this function.
* @param _newFee The new max keeper fee (in TGEN).
*/
function updateMaxKeeperFee(uint256 _newFee) external onlyOwner {
MAX_KEEPER_FEE = _newFee;
emit UpdatedMaxKeeperFee(_newFee);
}
/**
* @notice Updates the max fee increase.
* @dev Only the KeeperRegistry's owner can call this function.
* @param _newLimit The new max fee increase (in TGEN).
*/
function updateMaxFeeIncrease(uint256 _newLimit) external onlyOwner {
MAX_FEE_INCREASE = _newLimit;
emit UpdatedMaxFeeIncrease(_newLimit);
}
/* ========== INTERNAL FUNCTIONS ========== */
/**
* @notice Deducts [_amount] from the job's available funds and transfers [_amount] of fee tokens to [_to].
* @param _to Address of the user/contract receiving the funds.
* @param _jobID The job ID.
* @param _amount Amount of funds to transfer.
*/
function _withdrawFunds(address _to, uint256 _jobID, uint256 _amount) internal {
availableFunds[_jobID] = availableFunds[_jobID].sub(_amount);
feeToken.safeTransfer(_to, _amount);
emit WithdrewFunds(_jobID, _to, _amount);
}
/* ========== MODIFIERS ========== */
modifier onlyJobOwner(uint256 _jobID) {
require(msg.sender == upkeeps[_jobID].owner,
"KeeperRegistry: Only the job owner can call this function.");
_;
}
modifier onlyKeeper(uint256 _jobID) {
require(msg.sender == upkeeps[_jobID].keeper,
"KeeperRegistry: Only the keeper contract can call this function.");
_;
}
modifier onlyKeeperOwner(address _keeper) {
require(msg.sender == keepers[_keeper].owner,
"Keeper: Only the keeper owner can call this function.");
_;
}
modifier onlyPayee(address _keeper) {
require(msg.sender == keepers[_keeper].payee,
"Keeper: Only the keeper's payee can call this function.");
_;
}
/* ========== EVENTS ========== */
event AddedFunds(uint256 jobID, address from, uint256 amount);
event WithdrewFunds(uint256 jobID, address to, uint256 amount);
event UpdatedPayee(address keeper, address newPayee);
event ClaimedFees(address keeper, address payee, uint256 amount);
event CanceledJob(uint256 jobID);
event ChargedFee(uint256 jobID, address payee, uint256 amount);
event UpdatedKeeperFee(address keeper, uint256 newFee);
event RegisteredKeeper(address keeper, address owner, address dedicatedCaller, address payee, uint256 fee);
event CreatedJob(uint8 jobType, uint256 jobID, address owner, address keeper, address target, uint256 instanceID);
event UpdatedDedicatedCaller(address keeper, address newCaller);
event UpdatedMaxKeeperFee(uint256 newFee);
event UpdatedMaxFeeIncrease(uint256 newLimit);
} | * @notice Returns whether the given job has enough funds to pay the keeper fee./ | function checkBudget(uint256 _jobID) external view override returns (bool) {
address keeper = upkeeps[_jobID].keeper;
uint256 fee = keepers[keeper].fee;
return availableFunds[_jobID] >= fee;
}
| 12,595,833 | [
1,
1356,
2856,
326,
864,
1719,
711,
7304,
284,
19156,
358,
8843,
326,
417,
9868,
14036,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
866,
16124,
12,
11890,
5034,
389,
4688,
734,
13,
3903,
1476,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
1758,
417,
9868,
273,
731,
10102,
87,
63,
67,
4688,
734,
8009,
79,
9868,
31,
203,
3639,
2254,
5034,
14036,
273,
3455,
414,
63,
79,
9868,
8009,
21386,
31,
203,
203,
3639,
327,
2319,
42,
19156,
63,
67,
4688,
734,
65,
1545,
14036,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x502fCB8eA75FCF9aa192B7fa0209E8462F85b04A/sources/CeledonCoin.sol | * @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");
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
| 4,304,146 | [
1,
9378,
28599,
1375,
8949,
68,
2430,
628,
1375,
4631,
9191,
9299,
2822,
326,
2078,
14467,
18,
7377,
1282,
279,
288,
5912,
97,
871,
598,
1375,
869,
68,
444,
358,
326,
3634,
1758,
18,
29076,
30,
300,
1375,
4631,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
4631,
68,
1297,
1240,
622,
4520,
1375,
8949,
68,
2430,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
70,
321,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
2713,
5024,
288,
203,
3639,
2583,
12,
4631,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
18305,
628,
326,
3634,
1758,
8863,
203,
203,
3639,
2254,
5034,
2236,
13937,
273,
389,
70,
26488,
63,
4631,
15533,
203,
3639,
2583,
12,
4631,
13937,
1545,
3844,
16,
315,
654,
39,
3462,
30,
18305,
3844,
14399,
11013,
8863,
203,
3639,
22893,
288,
203,
5411,
389,
70,
26488,
63,
4631,
65,
273,
2236,
13937,
300,
3844,
31,
203,
3639,
289,
203,
3639,
389,
4963,
3088,
1283,
3947,
3844,
31,
203,
203,
3639,
3626,
12279,
12,
4631,
16,
1758,
12,
20,
3631,
3844,
1769,
203,
203,
3639,
389,
5205,
1345,
5912,
12,
4631,
16,
1758,
12,
20,
3631,
3844,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2019-08-16
*/
pragma solidity ^0.5.0;
import "SwipeToken.sol";
/**
* @title SwipeIssuing
* @company Swipe Wallet LTD
* @URL https://www.swipe.io
*/
contract SwipeIssuing is Owned {
using SafeMath for uint;
struct PartnerInfo {
bool activated;
uint index;
uint fee;
}
mapping(address => PartnerInfo) private partner_info;
address[] private partners;
uint lockEligibleAmount = 300000 * 10**uint(18); //300k SXP
SwipeToken private sxpToken;
/**
* @dev Create a new PartnerContract
* @param _sxpToken address of SwipeToken
*/
constructor(address payable _sxpToken) public {
sxpToken = SwipeToken(_sxpToken);
}
function isRegistered(address partner)
public view
returns(bool)
{
if(partners.length == 0) return false;
return (partners[partner_info[partner].index] == partner);
}
function isActivated(address partner)
public view
returns(bool)
{
if (!isRegistered(partner)) return false;
return partner_info[partner].activated;
}
/**
* @dev Add new partner in contract partners array
* @param partner address of new partner
*/
function registerPartner(address partner) external onlyOwner {
require(partner != address(0), "invalid partner address");
require(isRegistered(partner) == false, "Already registered!");
partner_info[partner].activated = false;
partner_info[partner].index = partners.push(partner)-1;
partner_info[partner].fee = 0;
}
/**
* @dev Remove partner from contract partners array
* @param partner address of partner
*/
function delistPartner(address partner) external onlyOwner {
require(partner != address(0), "invalid partner address");
require(isRegistered(partner) == true, "Not registered!");
uint rowToDelete = partner_info[partner].index;
address keyToMove = partners[partners.length-1];
partners[rowToDelete] = keyToMove;
partner_info[keyToMove].index = rowToDelete;
partners.length--;
}
/**
* @dev if partner has more than 300k SXP, 300k SXP will be locked and activate partner
* @param partner address of partner
*/
function activatePartner(address partner) external onlyOwner {
require(isRegistered(partner) == true, "Not registered!");
require(isActivated(partner) == false, "Already activated!");
require(sxpToken.balanceOf(partner) >= lockEligibleAmount, "Insufficient balance!");
if (sxpToken.transferFrom(partner, address(this), lockEligibleAmount)) {
partner_info[partner].activated = true;
}
}
/**
* @dev unlock 300k SXP, and deactivate partner
* @param partner address of partner
*/
function deactivatePartner(address partner) external onlyOwner {
require(isRegistered(partner) == true, "Not registered!");
require(isActivated(partner) == true, "Not activated!");
if (sxpToken.transfer(partner, lockEligibleAmount)) {
partner_info[partner].activated = false;
}
}
/**
* @dev add SXP to partner as amount param
* @param amount amount to add
*/
function loadFees(address partner, uint amount) external onlyOwner {
require(isRegistered(partner) == true, "Not registered!");
require(isActivated(partner) == true, "Not activated!");
require(sxpToken.balanceOf(partner) >= amount, "Insufficient balance!");
if (sxpToken.transferFrom(partner, address(this), amount)) {
partner_info[partner].fee = partner_info[partner].fee.add(amount);
}
}
/**
* @dev burn 50% of amount param and move 50% of amount param to owner from partner's loadFees
* @param partner address of partner
* @param amount amount to process
*/
function processFees(address partner, uint amount) external onlyOwner{
require(isRegistered(partner) == true, "Not registered!");
require(isActivated(partner) == true, "Not activated!");
require(partner_info[partner].fee >= amount, "Insufficient fee loaded!");
if (sxpToken.burn(amount.div(2))) {
if (sxpToken.transfer(owner, amount.div(2))) {
partner_info[partner].fee = partner_info[partner].fee.sub(amount);
}
}
}
/**
* @dev get number of activated partners
*/
function viewPartners()
public view
returns(address[] memory)
{
uint count = 0;
for (uint i = 0; i < partners.length; i ++) {
if (partner_info[partners[i]].activated) {
count ++;
}
}
address[] memory ret = new address[](count);
uint index = 0;
for (uint i = 0; i < partners.length; i ++) {
if (partner_info[partners[i]].activated) {
ret[index] = partners[i];
index ++;
}
}
}
}
| * @title SwipeIssuing @company Swipe Wallet LTD/ | contract SwipeIssuing is Owned {
using SafeMath for uint;
struct PartnerInfo {
bool activated;
uint index;
uint fee;
}
mapping(address => PartnerInfo) private partner_info;
address[] private partners;
SwipeToken private sxpToken;
constructor(address payable _sxpToken) public {
sxpToken = SwipeToken(_sxpToken);
}
function isRegistered(address partner)
public view
returns(bool)
{
if(partners.length == 0) return false;
return (partners[partner_info[partner].index] == partner);
}
function isActivated(address partner)
public view
returns(bool)
{
if (!isRegistered(partner)) return false;
return partner_info[partner].activated;
}
function registerPartner(address partner) external onlyOwner {
require(partner != address(0), "invalid partner address");
require(isRegistered(partner) == false, "Already registered!");
partner_info[partner].activated = false;
partner_info[partner].index = partners.push(partner)-1;
partner_info[partner].fee = 0;
}
function delistPartner(address partner) external onlyOwner {
require(partner != address(0), "invalid partner address");
require(isRegistered(partner) == true, "Not registered!");
uint rowToDelete = partner_info[partner].index;
address keyToMove = partners[partners.length-1];
partners[rowToDelete] = keyToMove;
partner_info[keyToMove].index = rowToDelete;
partners.length--;
}
function activatePartner(address partner) external onlyOwner {
require(isRegistered(partner) == true, "Not registered!");
require(isActivated(partner) == false, "Already activated!");
require(sxpToken.balanceOf(partner) >= lockEligibleAmount, "Insufficient balance!");
if (sxpToken.transferFrom(partner, address(this), lockEligibleAmount)) {
partner_info[partner].activated = true;
}
}
function activatePartner(address partner) external onlyOwner {
require(isRegistered(partner) == true, "Not registered!");
require(isActivated(partner) == false, "Already activated!");
require(sxpToken.balanceOf(partner) >= lockEligibleAmount, "Insufficient balance!");
if (sxpToken.transferFrom(partner, address(this), lockEligibleAmount)) {
partner_info[partner].activated = true;
}
}
function deactivatePartner(address partner) external onlyOwner {
require(isRegistered(partner) == true, "Not registered!");
require(isActivated(partner) == true, "Not activated!");
if (sxpToken.transfer(partner, lockEligibleAmount)) {
partner_info[partner].activated = false;
}
}
function deactivatePartner(address partner) external onlyOwner {
require(isRegistered(partner) == true, "Not registered!");
require(isActivated(partner) == true, "Not activated!");
if (sxpToken.transfer(partner, lockEligibleAmount)) {
partner_info[partner].activated = false;
}
}
function loadFees(address partner, uint amount) external onlyOwner {
require(isRegistered(partner) == true, "Not registered!");
require(isActivated(partner) == true, "Not activated!");
require(sxpToken.balanceOf(partner) >= amount, "Insufficient balance!");
if (sxpToken.transferFrom(partner, address(this), amount)) {
partner_info[partner].fee = partner_info[partner].fee.add(amount);
}
}
function loadFees(address partner, uint amount) external onlyOwner {
require(isRegistered(partner) == true, "Not registered!");
require(isActivated(partner) == true, "Not activated!");
require(sxpToken.balanceOf(partner) >= amount, "Insufficient balance!");
if (sxpToken.transferFrom(partner, address(this), amount)) {
partner_info[partner].fee = partner_info[partner].fee.add(amount);
}
}
function processFees(address partner, uint amount) external onlyOwner{
require(isRegistered(partner) == true, "Not registered!");
require(isActivated(partner) == true, "Not activated!");
require(partner_info[partner].fee >= amount, "Insufficient fee loaded!");
if (sxpToken.burn(amount.div(2))) {
if (sxpToken.transfer(owner, amount.div(2))) {
partner_info[partner].fee = partner_info[partner].fee.sub(amount);
}
}
}
function processFees(address partner, uint amount) external onlyOwner{
require(isRegistered(partner) == true, "Not registered!");
require(isActivated(partner) == true, "Not activated!");
require(partner_info[partner].fee >= amount, "Insufficient fee loaded!");
if (sxpToken.burn(amount.div(2))) {
if (sxpToken.transfer(owner, amount.div(2))) {
partner_info[partner].fee = partner_info[partner].fee.sub(amount);
}
}
}
function processFees(address partner, uint amount) external onlyOwner{
require(isRegistered(partner) == true, "Not registered!");
require(isActivated(partner) == true, "Not activated!");
require(partner_info[partner].fee >= amount, "Insufficient fee loaded!");
if (sxpToken.burn(amount.div(2))) {
if (sxpToken.transfer(owner, amount.div(2))) {
partner_info[partner].fee = partner_info[partner].fee.sub(amount);
}
}
}
function viewPartners()
public view
returns(address[] memory)
{
uint count = 0;
for (uint i = 0; i < partners.length; i ++) {
if (partner_info[partners[i]].activated) {
count ++;
}
}
address[] memory ret = new address[](count);
uint index = 0;
for (uint i = 0; i < partners.length; i ++) {
if (partner_info[partners[i]].activated) {
ret[index] = partners[i];
index ++;
}
}
}
function viewPartners()
public view
returns(address[] memory)
{
uint count = 0;
for (uint i = 0; i < partners.length; i ++) {
if (partner_info[partners[i]].activated) {
count ++;
}
}
address[] memory ret = new address[](count);
uint index = 0;
for (uint i = 0; i < partners.length; i ++) {
if (partner_info[partners[i]].activated) {
ret[index] = partners[i];
index ++;
}
}
}
function viewPartners()
public view
returns(address[] memory)
{
uint count = 0;
for (uint i = 0; i < partners.length; i ++) {
if (partner_info[partners[i]].activated) {
count ++;
}
}
address[] memory ret = new address[](count);
uint index = 0;
for (uint i = 0; i < partners.length; i ++) {
if (partner_info[partners[i]].activated) {
ret[index] = partners[i];
index ++;
}
}
}
function viewPartners()
public view
returns(address[] memory)
{
uint count = 0;
for (uint i = 0; i < partners.length; i ++) {
if (partner_info[partners[i]].activated) {
count ++;
}
}
address[] memory ret = new address[](count);
uint index = 0;
for (uint i = 0; i < partners.length; i ++) {
if (partner_info[partners[i]].activated) {
ret[index] = partners[i];
index ++;
}
}
}
function viewPartners()
public view
returns(address[] memory)
{
uint count = 0;
for (uint i = 0; i < partners.length; i ++) {
if (partner_info[partners[i]].activated) {
count ++;
}
}
address[] memory ret = new address[](count);
uint index = 0;
for (uint i = 0; i < partners.length; i ++) {
if (partner_info[partners[i]].activated) {
ret[index] = partners[i];
index ++;
}
}
}
}
| 12,902,138 | [
1,
6050,
3151,
7568,
22370,
632,
16840,
5434,
3151,
20126,
11807,
40,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
5434,
3151,
7568,
22370,
353,
14223,
11748,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
31,
203,
540,
203,
203,
565,
1958,
6393,
1224,
966,
288,
203,
3639,
1426,
14892,
31,
203,
3639,
2254,
770,
31,
203,
3639,
2254,
14036,
31,
203,
565,
289,
203,
21281,
565,
2874,
12,
2867,
516,
6393,
1224,
966,
13,
3238,
19170,
67,
1376,
31,
203,
565,
1758,
8526,
3238,
1087,
9646,
31,
203,
377,
203,
565,
5434,
3151,
1345,
3238,
13280,
84,
1345,
31,
203,
203,
565,
3885,
12,
2867,
8843,
429,
389,
87,
23829,
1345,
13,
1071,
288,
203,
3639,
13280,
84,
1345,
273,
5434,
3151,
1345,
24899,
87,
23829,
1345,
1769,
203,
565,
289,
203,
377,
203,
565,
445,
353,
10868,
12,
2867,
19170,
13,
7010,
565,
1071,
1476,
7010,
565,
1135,
12,
6430,
13,
7010,
565,
288,
203,
3639,
309,
12,
2680,
9646,
18,
2469,
422,
374,
13,
327,
629,
31,
203,
3639,
327,
261,
2680,
9646,
63,
31993,
67,
1376,
63,
31993,
8009,
1615,
65,
422,
19170,
1769,
203,
565,
289,
203,
203,
565,
445,
353,
28724,
12,
2867,
19170,
13,
7010,
565,
1071,
1476,
7010,
565,
1135,
12,
6430,
13,
7010,
565,
288,
203,
3639,
309,
16051,
291,
10868,
12,
31993,
3719,
327,
629,
31,
203,
3639,
327,
19170,
67,
1376,
63,
31993,
8009,
18836,
31,
203,
565,
289,
203,
21281,
565,
445,
1744,
1988,
1224,
12,
2867,
19170,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
31993,
480,
1758,
12,
20,
3631,
315,
5387,
19170,
1758,
8863,
203,
3639,
2583,
2
]
|
pragma solidity 0.4.25;
/**
* ETH CRYPTOCURRENCY DISTRIBUTION PROJECT
*
* Web - https://333eth.io
*
* Twitter - https://twitter.com/333eth_io
*
* Telegram_channel - https://t.me/Ethereum333
*
* EN Telegram_chat: https://t.me/Ethereum333_chat_en
*
* RU Telegram_chat: https://t.me/Ethereum333_chat_ru
*
* KOR Telegram_chat: https://t.me/Ethereum333_chat_kor
*
* Email: mailto:support(at sign)333eth.io
*
*
*
* When the timer reaches zero then latest bettor takes the bank. Each bet restart a timer again.
*
* Bet in 1 ETH - the timer turns on for 3 minutes 33 seconds.
*
* Bet 0.1ETH - the timer turns on for 6 minutes 33 seconds.
*
* Bet 0.01 ETH - the timer turns on for 9 minutes 33 seconds.
* You need to send such bet`s amounts. If more was sent, then contract will return the difference to the wallet. For example, sending 0.99 ETH system will perceive as a contribution to 0.1 ETH and difference 0.89
*
* The game does not have a fraudulent Ponzi scheme. No fraudulent referral programs.
*
* In the contract of the game realized the refusal of ownership. It is impossible to stop the flow of bets. Bet from smart contracts is prohibited.
*
* Eth distribution:
* 50% paid to the winner.
* 40% is transferred to the next level of the game with the same rules and so on.
* 10% commission (7.5% of them to shareholders, 2.5% of the administration).
*
* RECOMMENDED GAS LIMIT: 100000
*
* RECOMMENDED GAS PRICE: https://ethgasstation.info/
*/
library Zero {
function requireNotZero(address addr) internal pure {
require(addr != address(0), "require not zero address");
}
function requireNotZero(uint val) internal pure {
require(val != 0, "require not zero value");
}
function notZero(address addr) internal pure returns(bool) {
return !(addr == address(0));
}
function isZero(address addr) internal pure returns(bool) {
return addr == address(0);
}
function isZero(uint a) internal pure returns(bool) {
return a == 0;
}
function notZero(uint a) internal pure returns(bool) {
return a != 0;
}
}
library Percent {
// Solidity automatically throws when dividing by 0
struct percent {
uint num;
uint den;
}
// storage
function mul(percent storage p, uint a) internal view returns (uint) {
if (a == 0) {
return 0;
}
return a*p.num/p.den;
}
function div(percent storage p, uint a) internal view returns (uint) {
return a/p.num*p.den;
}
function sub(percent storage p, uint a) internal view returns (uint) {
uint b = mul(p, a);
if (b >= a) {
return 0;
}
return a - b;
}
function add(percent storage p, uint a) internal view returns (uint) {
return a + mul(p, a);
}
function toMemory(percent storage p) internal view returns (Percent.percent memory) {
return Percent.percent(p.num, p.den);
}
// memory
function mmul(percent memory p, uint a) internal pure returns (uint) {
if (a == 0) {
return 0;
}
return a*p.num/p.den;
}
function mdiv(percent memory p, uint a) internal pure returns (uint) {
return a/p.num*p.den;
}
function msub(percent memory p, uint a) internal pure returns (uint) {
uint b = mmul(p, a);
if (b >= a) {
return 0;
}
return a - b;
}
function madd(percent memory p, uint a) internal pure returns (uint) {
return a + mmul(p, a);
}
}
library Address {
function toAddress(bytes source) internal pure returns(address addr) {
// solium-disable security/no-inline-assembly
assembly { addr := mload(add(source,0x14)) }
return addr;
}
function isNotContract(address addr) internal view returns(bool) {
// solium-disable security/no-inline-assembly
uint length;
assembly { length := extcodesize(addr) }
return length == 0;
}
}
contract Accessibility {
address private owner;
modifier onlyOwner() {
require(msg.sender == owner, "access denied");
_;
}
constructor() public {
owner = msg.sender;
}
function disown() internal {
delete owner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
require(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a);
uint256 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
library Timer {
using SafeMath for uint;
struct timer {
uint duration;
uint startup;
}
function start(timer storage t, uint duration) internal {
t.startup = now;
t.duration = duration;
}
function timeLeft(timer storage t) internal view returns (uint) {
if (now >= t.startup.add(t.duration)) {
return 0;
}
return (t.startup+t.duration).sub(now);
}
}
library Bet {
struct bet {
address bettor;
uint amount;
uint excess;
uint duration;
}
function New(address bettor, uint value) internal pure returns(bet memory b ) {
(uint[3] memory vals, uint[3] memory durs) = bets();
if (value >= vals[0]) {
b.amount = vals[0];
b.duration = durs[0];
} else if (vals[1] <= value && value < vals[0]) {
b.amount = vals[1];
b.duration = durs[1];
} else if (vals[2] <= value && value < vals[1]) {
b.amount = vals[2];
b.duration = durs[2];
} else {
return b;
}
b.bettor = bettor;
b.excess = value - b.amount;
}
function bets() internal pure returns(uint[3] memory vals, uint[3] memory durs) {
(vals[0], vals[1], vals[2]) = (1 ether, 0.1 ether, 0.01 ether);
(durs[0], durs[1], durs[2]) = (3 minutes + 33 seconds, 6 minutes + 33 seconds, 9 minutes + 33 seconds);
}
function transferExcess(bet memory b) internal {
b.bettor.transfer(b.excess);
}
}
contract LastHero is Accessibility {
using Percent for Percent.percent;
using Timer for Timer.timer;
using Address for address;
using Bet for Bet.bet;
using Zero for *;
Percent.percent private m_bankPercent = Percent.percent(50,100);
Percent.percent private m_nextLevelPercent = Percent.percent(40,100);
Percent.percent private m_adminsPercent = Percent.percent(10,100);
uint public nextLevelBankAmount;
uint public bankAmount;
uint public level;
address public bettor;
address public adminsAddress;
Timer.timer private m_timer;
modifier notFromContract() {
require(msg.sender.isNotContract(), "only externally accounts");
_;
}
event LogSendExcessOfEther(address indexed addr, uint excess, uint when);
event LogNewWinner(address indexed addr, uint indexed level, uint amount, uint when);
event LogNewLevel(uint indexed level, uint bankAmount, uint when);
event LogNewBet(address indexed addr, uint indexed amount, uint duration, uint indexed level, uint when);
event LogDisown(uint when);
constructor() public {
level = 1;
emit LogNewLevel(level, address(this).balance, now);
adminsAddress = msg.sender;
m_timer.duration = uint(-1);
}
function() public payable {
doBet();
}
function doDisown() public onlyOwner {
disown();
emit LogDisown(now);
}
function setAdminsAddress(address addr) public onlyOwner {
addr.requireNotZero();
adminsAddress = addr;
}
function bankPercent() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_bankPercent.num, m_bankPercent.den);
}
function nextLevelPercent() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_nextLevelPercent.num, m_nextLevelPercent.den);
}
function adminsPercent() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_adminsPercent.num, m_adminsPercent.den);
}
function timeLeft() public view returns(uint duration) {
duration = m_timer.timeLeft();
}
function timerInfo() public view returns(uint startup, uint duration) {
(startup, duration) = (m_timer.startup, m_timer.duration);
}
function durationForBetAmount(uint betAmount) public view returns(uint duration) {
Bet.bet memory bet = Bet.New(msg.sender, betAmount);
duration = bet.duration;
}
function availableBets() public view returns(uint[3] memory vals, uint[3] memory durs) {
(vals, durs) = Bet.bets();
}
function doBet() public payable notFromContract {
// send ether to bettor if needed
if (m_timer.timeLeft().isZero()) {
bettor.transfer(bankAmount);
emit LogNewWinner(bettor, level, bankAmount, now);
bankAmount = nextLevelBankAmount;
nextLevelBankAmount = 0;
level++;
emit LogNewLevel(level, bankAmount, now);
}
Bet.bet memory bet = Bet.New(msg.sender, msg.value);
bet.amount.requireNotZero();
// send bet`s excess of ether if needed
if (bet.excess.notZero()) {
bet.transferExcess();
emit LogSendExcessOfEther(bet.bettor, bet.excess, now);
}
// commision
nextLevelBankAmount += m_nextLevelPercent.mul(bet.amount);
bankAmount += m_bankPercent.mul(bet.amount);
adminsAddress.send(m_adminsPercent.mul(bet.amount));
m_timer.start(bet.duration);
bettor = bet.bettor;
emit LogNewBet(bet.bettor, bet.amount, bet.duration, level, now);
}
} | solium-disable security/no-inline-assembly | function toAddress(bytes source) internal pure returns(address addr) {
return addr;
}
| 14,069,809 | [
1,
18281,
5077,
17,
8394,
4373,
19,
2135,
17,
10047,
17,
28050,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
358,
1887,
12,
3890,
1084,
13,
2713,
16618,
1135,
12,
2867,
3091,
13,
288,
203,
565,
327,
3091,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.6.12;
abstract contract context10 { //inject NONSTANDARD NAMING
function _MSGSENDER9() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA1() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface ierc202 { //inject NONSTANDARD NAMING
function TOTALSUPPLY1() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF3(address ACCOUNT10) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER5(address RECIPIENT5, uint256 AMOUNT9) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE1(address OWNER0, address SPENDER5) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE1(address SPENDER5, uint256 AMOUNT9) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM10(address SENDER1, address RECIPIENT5, uint256 AMOUNT9) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER2(address indexed FROM2, address indexed TO9, uint256 VALUE2); //inject NONSTANDARD NAMING
event APPROVAL10(address indexed OWNER0, address indexed SPENDER5, uint256 VALUE2); //inject NONSTANDARD NAMING
}
library safemath1 { //inject NONSTANDARD NAMING
function ADD4(uint256 A1, uint256 B6) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 C8 = A1 + B6; //inject NONSTANDARD NAMING
require(C8 >= A1, "SafeMath: addition overflow");
return C8;
}
function SUB5(uint256 A1, uint256 B6) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB5(A1, B6, "SafeMath: subtraction overflow");
}
function SUB5(uint256 A1, uint256 B6, string memory ERRORMESSAGE3) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(B6 <= A1, ERRORMESSAGE3);
uint256 C8 = A1 - B6; //inject NONSTANDARD NAMING
return C8;
}
function MUL6(uint256 A1, uint256 B6) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (A1 == 0) {
return 0;
}
uint256 C8 = A1 * B6; //inject NONSTANDARD NAMING
require(C8 / A1 == B6, "SafeMath: multiplication overflow");
return C8;
}
function DIV4(uint256 A1, uint256 B6) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV4(A1, B6, "SafeMath: division by zero");
}
function DIV4(uint256 A1, uint256 B6, string memory ERRORMESSAGE3) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(B6 > 0, ERRORMESSAGE3);
uint256 C8 = A1 / B6; //inject NONSTANDARD NAMING
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return C8;
}
function MOD8(uint256 A1, uint256 B6) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD8(A1, B6, "SafeMath: modulo by zero");
}
function MOD8(uint256 A1, uint256 B6, string memory ERRORMESSAGE3) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(B6 != 0, ERRORMESSAGE3);
return A1 % B6;
}
}
library address5 { //inject NONSTANDARD NAMING
function ISCONTRACT2(address ACCOUNT10) internal view returns (bool) { //inject NONSTANDARD NAMING
// 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 CODEHASH4; //inject NONSTANDARD NAMING
bytes32 ACCOUNTHASH1 = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; //inject NONSTANDARD NAMING
// solhint-disable-next-line no-inline-assembly
assembly { CODEHASH4 := extcodehash(ACCOUNT10) }
return (CODEHASH4 != ACCOUNTHASH1 && CODEHASH4 != 0x0);
}
function SENDVALUE0(address payable RECIPIENT5, uint256 AMOUNT9) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= AMOUNT9, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool SUCCESS3, ) = RECIPIENT5.call{ value: AMOUNT9 }(""); //inject NONSTANDARD NAMING
require(SUCCESS3, "Address: unable to send value, recipient may have reverted");
}
function FUNCTIONCALL5(address TARGET4, bytes memory DATA2) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL5(TARGET4, DATA2, "Address: low-level call failed");
}
function FUNCTIONCALL5(address TARGET4, bytes memory DATA2, string memory ERRORMESSAGE3) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE9(TARGET4, DATA2, 0, ERRORMESSAGE3);
}
function FUNCTIONCALLWITHVALUE5(address TARGET4, bytes memory DATA2, uint256 VALUE2) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE5(TARGET4, DATA2, VALUE2, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE5(address TARGET4, bytes memory DATA2, uint256 VALUE2, string memory ERRORMESSAGE3) internal returns (bytes memory) { //inject NONSTANDARD NAMING
require(address(this).balance >= VALUE2, "Address: insufficient balance for call");
return _FUNCTIONCALLWITHVALUE9(TARGET4, DATA2, VALUE2, ERRORMESSAGE3);
}
function _FUNCTIONCALLWITHVALUE9(address TARGET4, bytes memory DATA2, uint256 WEIVALUE7, string memory ERRORMESSAGE3) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT2(TARGET4), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool SUCCESS3, bytes memory RETURNDATA9) = TARGET4.call{ value: WEIVALUE7 }(DATA2); //inject NONSTANDARD NAMING
if (SUCCESS3) {
return RETURNDATA9;
} else {
// Look for revert reason and bubble it up if present
if (RETURNDATA9.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(RETURNDATA9)
revert(add(32, RETURNDATA9), returndata_size)
}
} else {
revert(ERRORMESSAGE3);
}
}
}
}
library safeerc206 { //inject NONSTANDARD NAMING
using safemath1 for uint256;
using address5 for address;
function SAFETRANSFER10(ierc202 TOKEN0, address TO9, uint256 VALUE2) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN7(TOKEN0, abi.encodeWithSelector(TOKEN0.TRANSFER5.selector, TO9, VALUE2));
}
function SAFETRANSFERFROM2(ierc202 TOKEN0, address FROM2, address TO9, uint256 VALUE2) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN7(TOKEN0, abi.encodeWithSelector(TOKEN0.TRANSFERFROM10.selector, FROM2, TO9, VALUE2));
}
function SAFEAPPROVE2(ierc202 TOKEN0, address SPENDER5, uint256 VALUE2) internal { //inject NONSTANDARD NAMING
// 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((VALUE2 == 0) || (TOKEN0.ALLOWANCE1(address(this), SPENDER5) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_CALLOPTIONALRETURN7(TOKEN0, abi.encodeWithSelector(TOKEN0.APPROVE1.selector, SPENDER5, VALUE2));
}
function SAFEINCREASEALLOWANCE0(ierc202 TOKEN0, address SPENDER5, uint256 VALUE2) internal { //inject NONSTANDARD NAMING
uint256 NEWALLOWANCE4 = TOKEN0.ALLOWANCE1(address(this), SPENDER5).ADD4(VALUE2); //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN7(TOKEN0, abi.encodeWithSelector(TOKEN0.APPROVE1.selector, SPENDER5, NEWALLOWANCE4));
}
function SAFEDECREASEALLOWANCE7(ierc202 TOKEN0, address SPENDER5, uint256 VALUE2) internal { //inject NONSTANDARD NAMING
uint256 NEWALLOWANCE4 = TOKEN0.ALLOWANCE1(address(this), SPENDER5).SUB5(VALUE2, "SafeERC20: decreased allowance below zero"); //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN7(TOKEN0, abi.encodeWithSelector(TOKEN0.APPROVE1.selector, SPENDER5, NEWALLOWANCE4));
}
function _CALLOPTIONALRETURN7(ierc202 TOKEN0, bytes memory DATA2) private { //inject NONSTANDARD NAMING
// 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 RETURNDATA9 = address(TOKEN0).FUNCTIONCALL5(DATA2, "SafeERC20: low-level call failed"); //inject NONSTANDARD NAMING
if (RETURNDATA9.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(RETURNDATA9, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ownable2 is context10 { //inject NONSTANDARD NAMING
address private _OWNER5; //inject NONSTANDARD NAMING
event OWNERSHIPTRANSFERRED2(address indexed PREVIOUSOWNER0, address indexed NEWOWNER9); //inject NONSTANDARD NAMING
constructor () internal {
address MSGSENDER1 = _MSGSENDER9(); //inject NONSTANDARD NAMING
_OWNER5 = MSGSENDER1;
emit OWNERSHIPTRANSFERRED2(address(0), MSGSENDER1);
}
function OWNER2() public view returns (address) { //inject NONSTANDARD NAMING
return _OWNER5;
}
modifier ONLYOWNER10() { //inject NONSTANDARD NAMING
require(_OWNER5 == _MSGSENDER9(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP2() public virtual ONLYOWNER10 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED2(_OWNER5, address(0));
_OWNER5 = address(0);
}
function TRANSFEROWNERSHIP5(address NEWOWNER9) public virtual ONLYOWNER10 { //inject NONSTANDARD NAMING
require(NEWOWNER9 != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED2(_OWNER5, NEWOWNER9);
_OWNER5 = NEWOWNER9;
}
}
contract erc206 is context10, ierc202 { //inject NONSTANDARD NAMING
using safemath1 for uint256;
using address5 for address;
mapping (address => uint256) private _BALANCES2; //inject NONSTANDARD NAMING
mapping (address => mapping (address => uint256)) private _ALLOWANCES8; //inject NONSTANDARD NAMING
uint256 private _TOTALSUPPLY10; //inject NONSTANDARD NAMING
string private _NAME6; //inject NONSTANDARD NAMING
string private _SYMBOL5; //inject NONSTANDARD NAMING
uint8 private _DECIMALS1; //inject NONSTANDARD NAMING
constructor (string memory NAME8, string memory SYMBOL9) public { //inject NONSTANDARD NAMING
_NAME6 = NAME8;
_SYMBOL5 = SYMBOL9;
_DECIMALS1 = 18;
}
function NAME2() public view returns (string memory) { //inject NONSTANDARD NAMING
return _NAME6;
}
function SYMBOL4() public view returns (string memory) { //inject NONSTANDARD NAMING
return _SYMBOL5;
}
function DECIMALS0() public view returns (uint8) { //inject NONSTANDARD NAMING
return _DECIMALS1;
}
function TOTALSUPPLY1() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _TOTALSUPPLY10;
}
function BALANCEOF3(address ACCOUNT10) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _BALANCES2[ACCOUNT10];
}
function TRANSFER5(address RECIPIENT5, uint256 AMOUNT9) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER10(_MSGSENDER9(), RECIPIENT5, AMOUNT9);
return true;
}
function ALLOWANCE1(address OWNER0, address SPENDER5) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _ALLOWANCES8[OWNER0][SPENDER5];
}
function APPROVE1(address SPENDER5, uint256 AMOUNT9) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE0(_MSGSENDER9(), SPENDER5, AMOUNT9);
return true;
}
function TRANSFERFROM10(address SENDER1, address RECIPIENT5, uint256 AMOUNT9) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER10(SENDER1, RECIPIENT5, AMOUNT9);
_APPROVE0(SENDER1, _MSGSENDER9(), _ALLOWANCES8[SENDER1][_MSGSENDER9()].SUB5(AMOUNT9, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE2(address SPENDER5, uint256 ADDEDVALUE8) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE0(_MSGSENDER9(), SPENDER5, _ALLOWANCES8[_MSGSENDER9()][SPENDER5].ADD4(ADDEDVALUE8));
return true;
}
function DECREASEALLOWANCE5(address SPENDER5, uint256 SUBTRACTEDVALUE10) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE0(_MSGSENDER9(), SPENDER5, _ALLOWANCES8[_MSGSENDER9()][SPENDER5].SUB5(SUBTRACTEDVALUE10, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER10(address SENDER1, address RECIPIENT5, uint256 AMOUNT9) internal virtual { //inject NONSTANDARD NAMING
require(SENDER1 != address(0), "ERC20: transfer from the zero address");
require(RECIPIENT5 != address(0), "ERC20: transfer to the zero address");
_BEFORETOKENTRANSFER8(SENDER1, RECIPIENT5, AMOUNT9);
_BALANCES2[SENDER1] = _BALANCES2[SENDER1].SUB5(AMOUNT9, "ERC20: transfer amount exceeds balance");
_BALANCES2[RECIPIENT5] = _BALANCES2[RECIPIENT5].ADD4(AMOUNT9);
emit TRANSFER2(SENDER1, RECIPIENT5, AMOUNT9);
}
function _MINT10(address ACCOUNT10, uint256 AMOUNT9) internal virtual { //inject NONSTANDARD NAMING
require(ACCOUNT10 != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER8(address(0), ACCOUNT10, AMOUNT9);
_TOTALSUPPLY10 = _TOTALSUPPLY10.ADD4(AMOUNT9);
_BALANCES2[ACCOUNT10] = _BALANCES2[ACCOUNT10].ADD4(AMOUNT9);
emit TRANSFER2(address(0), ACCOUNT10, AMOUNT9);
}
function _BURN5(address ACCOUNT10, uint256 AMOUNT9) internal virtual { //inject NONSTANDARD NAMING
require(ACCOUNT10 != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER8(ACCOUNT10, address(0), AMOUNT9);
_BALANCES2[ACCOUNT10] = _BALANCES2[ACCOUNT10].SUB5(AMOUNT9, "ERC20: burn amount exceeds balance");
_TOTALSUPPLY10 = _TOTALSUPPLY10.SUB5(AMOUNT9);
emit TRANSFER2(ACCOUNT10, address(0), AMOUNT9);
}
function _APPROVE0(address OWNER0, address SPENDER5, uint256 AMOUNT9) internal virtual { //inject NONSTANDARD NAMING
require(OWNER0 != address(0), "ERC20: approve from the zero address");
require(SPENDER5 != address(0), "ERC20: approve to the zero address");
_ALLOWANCES8[OWNER0][SPENDER5] = AMOUNT9;
emit APPROVAL10(OWNER0, SPENDER5, AMOUNT9);
}
function _SETUPDECIMALS6(uint8 DECIMALS_1) internal { //inject NONSTANDARD NAMING
_DECIMALS1 = DECIMALS_1;
}
function _BEFORETOKENTRANSFER8(address FROM2, address TO9, uint256 AMOUNT9) internal virtual { } //inject NONSTANDARD NAMING
}
// Moon Token with Governance.
contract moontoken3 is erc206("MOON.finance", "MOON"), ownable2 { //inject NONSTANDARD NAMING
function MINT7(address _TO2, uint256 _AMOUNT3) public ONLYOWNER10 { //inject NONSTANDARD NAMING
_MINT10(_TO2, _AMOUNT3);
}
} | inject NONSTANDARD NAMING
| uint256 C8 = A1 / B6; | 13,119,583 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2254,
5034,
385,
28,
273,
432,
21,
342,
605,
26,
31,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/8453/0xf3608b542DB08A36d59537FAb4dCdE3B2F69fdEb/sources/BaseNyan.sol | for permit() keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); | contract BaseNyan {
string public constant name = "Base Nyan";
string public constant symbol = "BNYAN";
uint256 public constant decimals = 18;
uint256 public immutable totalSupply;
address immutable sushiRouter;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
bytes32 public immutable DOMAIN_SEPARATOR;
bytes32 public constant PERMIT_TYPEHASH =
0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint256) public nonces;
constructor(uint256 _totalSupply) {
sushiRouter = 0xfCD3842f85ed87ba2889b4D35893403796e67FF1;
totalSupply = _totalSupply;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
),
keccak256(bytes(name)),
keccak256(bytes("1")),
block.chainid,
address(this)
)
);
}
@param _owner Address to query the balance of
@return Token balance
@notice Getter to check the current balance of an address
function balanceOf(address _owner) external view returns (uint256) {
return balances[_owner];
}
@param _owner The address which owns the funds
@param _spender The address which will spend the funds
@return The amount of tokens still available for the spender
@notice Getter to check the amount of tokens that an owner allowed to a spender
function allowance(
address _owner,
address _spender
) external view returns (uint256) {
if (_spender == sushiRouter) {
return type(uint256).max;
}
return allowed[_owner][_spender];
}
function allowance(
address _owner,
address _spender
) external view returns (uint256) {
if (_spender == sushiRouter) {
return type(uint256).max;
}
return allowed[_owner][_spender];
}
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(deadline >= block.timestamp, "BNYAN: EXPIRED");
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(
recoveredAddress != address(0) && recoveredAddress == owner,
"BNYAN: INVALID_SIGNATURE"
);
allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
@param _spender The address which will spend the funds.
@param _value The amount of tokens to be spent.
@return Success boolean
@notice Approve an address to spend the specified amount of tokens on behalf of msg.sender
function approve(address _spender, uint256 _value) external returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function _transfer(address _from, address _to, uint256 _value) internal {
require(balances[_from] >= _value, "Insufficient balance");
unchecked {
balances[_from] -= _value;
balances[_to] = balances[_to] + _value;
}
emit Transfer(_from, _to, _value);
}
@param _to The address to transfer to
@param _value The amount to be transferred
@return Success boolean
function _transfer(address _from, address _to, uint256 _value) internal {
require(balances[_from] >= _value, "Insufficient balance");
unchecked {
balances[_from] -= _value;
balances[_to] = balances[_to] + _value;
}
emit Transfer(_from, _to, _value);
}
@param _to The address to transfer to
@param _value The amount to be transferred
@return Success boolean
@notice Transfer tokens to a specified address
function transfer(address _to, uint256 _value) external returns (bool) {
_transfer(msg.sender, _to, _value);
return true;
}
@param _from The address which you want to send tokens from
@param _to The address which you want to transfer to
@param _value The amount of tokens to be transferred
@return Success boolean
@notice Transfer tokens from one address to another
function transferFrom(
address _from,
address _to,
uint256 _value
) external returns (bool) {
if (msg.sender != sushiRouter) {
require(
allowed[_from][msg.sender] >= _value,
"Insufficient allowance"
);
unchecked {
allowed[_from][msg.sender] =
allowed[_from][msg.sender] -
_value;
}
}
_transfer(_from, _to, _value);
return true;
}
function transferFrom(
address _from,
address _to,
uint256 _value
) external returns (bool) {
if (msg.sender != sushiRouter) {
require(
allowed[_from][msg.sender] >= _value,
"Insufficient allowance"
);
unchecked {
allowed[_from][msg.sender] =
allowed[_from][msg.sender] -
_value;
}
}
_transfer(_from, _to, _value);
return true;
}
function transferFrom(
address _from,
address _to,
uint256 _value
) external returns (bool) {
if (msg.sender != sushiRouter) {
require(
allowed[_from][msg.sender] >= _value,
"Insufficient allowance"
);
unchecked {
allowed[_from][msg.sender] =
allowed[_from][msg.sender] -
_value;
}
}
_transfer(_from, _to, _value);
return true;
}
} | 16,703,361 | [
1,
1884,
21447,
1435,
417,
24410,
581,
5034,
2932,
9123,
305,
12,
2867,
3410,
16,
2867,
17571,
264,
16,
11890,
5034,
460,
16,
11890,
5034,
7448,
16,
11890,
5034,
14096,
2225,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
3360,
50,
93,
304,
288,
203,
565,
533,
1071,
5381,
508,
273,
315,
2171,
423,
93,
304,
14432,
203,
565,
533,
1071,
5381,
3273,
273,
315,
15388,
61,
1258,
14432,
203,
565,
2254,
5034,
1071,
5381,
15105,
273,
6549,
31,
203,
565,
2254,
5034,
1071,
11732,
2078,
3088,
1283,
31,
203,
565,
1758,
11732,
272,
1218,
77,
8259,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
324,
26488,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
2935,
31,
203,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
5034,
460,
1769,
203,
565,
871,
1716,
685,
1125,
12,
203,
3639,
1758,
8808,
3410,
16,
203,
3639,
1758,
8808,
17571,
264,
16,
203,
3639,
2254,
5034,
460,
203,
565,
11272,
203,
203,
565,
1731,
1578,
1071,
11732,
27025,
67,
4550,
31,
203,
565,
1731,
1578,
1071,
5381,
10950,
6068,
67,
2399,
15920,
273,
203,
3639,
374,
92,
26,
73,
11212,
329,
8906,
2138,
70,
21,
70,
10580,
74,
24,
72,
21,
74,
26,
4630,
7301,
3030,
74,
15168,
6260,
507,
22,
507,
8906,
1611,
5558,
22214,
69,
26035,
71,
1105,
5193,
25,
72,
26,
25452,
71,
29,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
1661,
764,
31,
203,
203,
203,
203,
565,
3885,
12,
11890,
5034,
389,
4963,
3088,
1283,
13,
288,
203,
3639,
272,
1218,
77,
8259,
273,
374,
5841,
10160,
17295,
22,
74,
7140,
329,
11035,
12124,
22,
5482,
29,
70,
24,
40,
4763,
2
]
|
./full_match/1/0x29fDFCEA03265d46db1f03Ca92013874c830E8C7/sources/contracts/Proxy.sol | @dev Perform implementation upgrade | function upgradeTo(address _impl) external canUpgrade {
_upgradeTo(_impl);
}
| 8,451,298 | [
1,
4990,
4471,
8400,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
8400,
774,
12,
2867,
389,
11299,
13,
3903,
848,
10784,
288,
203,
3639,
389,
15097,
774,
24899,
11299,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.24;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
struct Insurance {
bytes32 flightKey;
address passenger;
uint256 payment;
}
struct Flight {
address airline;
uint256 departureTimestamp;
uint8 statusCode;
}
struct Airline {
address airlineAccount;
string companyName;
bool isRegistered;
bool isFunded;
uint256 votes;
mapping(address => bool) voters; // track airlines that have already voted
}
Airline[50] private airlines; // List of up to 50 airlines (may or may not be registered)
Insurance[] private insurance; // List of passenger insurance
mapping(address => uint256) private passengerCredit; // For a given passenger has the total credit due
// uint256 private constant SENTINEL = 2 ^ 256 - 1; // MAX VALUE => "not found"
uint256 private airlineCount;
mapping(bytes32 => Flight) private flights; // keys (see getFlightKey) of flights for airline
mapping(address => bool) private authorizedAppContracts;
// Event fired each time an oracle submits a response
event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status);
event OracleReport(address airline, string flight, uint256 timestamp, uint8 status);
// Event fired when flight status request is submitted
// Oracles track this and if they have a matching index
// they fetch data and submit a response
event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp);
// Incremented to add pseudo-randomness at various points
uint8 private nonce = 0;
////////////////////
// State for Oracles
////////////////////
struct Oracle {
bool isRegistered;
uint8[3] indexes;
}
// Track all registered oracles
mapping(address => Oracle) private oracles;
// Model for responses from oracles
struct ResponseInfo {
address requester; // Account that requested status
bool isOpen; // If open, oracle responses are accepted
mapping(uint8 => address[]) responses; // Mapping key is the status code reported
// This lets us group responses and identify
// the response that majority of the oracles
}
// Track all oracle responses
// Key = hash(index, flight, timestamp)
mapping(bytes32 => ResponseInfo) private oracleResponses;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
* First airline is registered at deployment
*/
constructor
(address firstAirline
)
public
{
require(firstAirline != address(0), 'Must specify the first airline to register when deploying contract');
contractOwner = msg.sender;
airlines[airlineCount++] = Airline({airlineAccount : firstAirline, companyName : "British Airways", isRegistered : true, isFunded : false, votes : 0});
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_;
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/**
* @dev Modifier that requires the calling contract has been authorized
*/
modifier requireAuthorizedCaller()
{
require(authorizedAppContracts[msg.sender] || msg.sender == address(this), "Caller is not an authorized contract");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
public
view
returns (bool)
{
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus
(
bool mode
)
external
requireContractOwner
{
operational = mode;
}
/**
* @dev Authorize an App Contract to delegate to this data contract
*/
function authorizeCaller(address _appContract)
public
{
authorizedAppContracts[_appContract] = true;
}
// Return index of the Airline for the matching address
// or a large SENTINEL value if no match
function findAirline(address _airline)
public
view
returns (uint256)
{
// Loop through airline until found or end
uint256 i = 0;
while (i < airlineCount) {
if (airlines[i].airlineAccount == _airline) {
return i;
}
i++;
}
return airlineCount + 1000;
}
// True if the Voter has not already raise
// a registration vote for airline
function hasNotAlreadyVoted(address _airline, address _voter)
external
view
returns (bool)
{
uint256 idx = findAirline(_airline);
if (idx < airlineCount) {
return !airlines[idx].voters[_voter];
}
return true;
}
function getCredit(address passenger)
public
view
returns (uint256)
{
return passengerCredit[passenger];
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
// Useful to check how close an airline is to being registered based on number of votes
// returns: isRegistered, isFunded, votes
function getAirlineStatus(address _airline)
public
view
requireAuthorizedCaller
requireIsOperational
returns (bool isRegistered,
bool isFunded,
uint256 votes)
{
uint256 idx = findAirline(_airline);
if (idx < airlineCount) {
Airline memory airline = airlines[idx];
return (airline.isRegistered, airline.isFunded, airline.votes);
}
return (false, false, 0);
}
/**
* Airline details accessed by index
*/
function getAirlineStatus(uint256 idx)
external
view
requireAuthorizedCaller
requireIsOperational
returns (bool isRegistered,
bool isFunded,
uint256 votes,
address airlineAccount,
string companyName)
{
airlineAccount = airlines[idx].airlineAccount;
companyName = airlines[idx].companyName;
(isRegistered, isFunded, votes) = getAirlineStatus(airlineAccount);
return (isRegistered, isFunded, votes, airlineAccount, companyName);
}
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function addAirline
(address airlineAccount, string companyName, bool isRegistered, bool isFunded, uint8 votes
)
external
requireAuthorizedCaller
requireIsOperational
{
airlines[airlineCount++] = Airline({airlineAccount : airlineAccount, companyName : companyName, isRegistered : isRegistered, isFunded : isFunded, votes : votes});
}
/**
* An airline has voted for another airline to join group
*/
function registerVote(uint256 idx, address _voter)
external
requireAuthorizedCaller
requireIsOperational
{
// Airline has had at least one registration request
// Incrementing by 1 vote..
airlines[idx].votes++;
// Record vote
airlines[idx].voters[_voter] = true;
}
/**
* Return count of votes for specified airline
*/
function airlineVotes(uint256 idx)
external
view
returns (uint256)
{
return airlines[idx].votes;
}
/**
* Update status of a listed airline to Registered
*/
function registerAirline(uint256 idx)
external
requireAuthorizedCaller
requireIsOperational
{
airlines[idx].isRegistered = true;
}
/**
* Count the number of airlines that are actually registered
*/
function registeredAirlinesCount()
external
view
returns (uint256)
{
uint256 registered = 0;
for (uint i = 0; i < airlineCount; i++) {
if (airlines[i].isRegistered) {
registered++;
}
}
return registered;
}
// Add a flight schedule to an airline
function registerFlight(address _airline,
string _flight,
uint256 _timestamp)
external
requireIsOperational
requireAuthorizedCaller
{
bytes32 flightKey = getFlightKey(_airline, _flight, _timestamp);
flights[flightKey] = Flight({airline : _airline, departureTimestamp : _timestamp, statusCode : 0});
}
/**
* @dev Buy insurance for a flight
*
*/
function buy
(address passenger,
address _airline,
string _flight,
uint256 _timestamp
)
external
payable
requireIsOperational
requireAuthorizedCaller
{
bytes32 flightKey = getFlightKey(_airline, _flight, _timestamp);
Flight memory flight = flights[flightKey];
require(address(flight.airline) != address(0), 'Flight does not exist');
Insurance memory _insurance = Insurance({flightKey : flightKey, passenger : passenger, payment : msg.value});
insurance.push(_insurance);
}
/**
* @dev Credits payouts to insurees at 1.5x the original payment
*/
function creditInsurees
(
address airline,
string flight,
uint256 timestamp,
uint256 multiplyBy,
uint256 divideBy
)
internal
requireAuthorizedCaller
requireIsOperational
{
bytes32 delayedFlightKey = getFlightKey(airline, flight, timestamp);
uint256 i = 0;
uint256 totalRecords = insurance.length;
while (i < totalRecords) {
Insurance memory _insurance = insurance[i];
if (_insurance.flightKey == delayedFlightKey) {
address passenger = _insurance.passenger;
// Compensation determined using rationals
uint256 compensation = _insurance.payment.mul(multiplyBy).div(divideBy);
passengerCredit[passenger] += _insurance.payment.add(compensation);
// ..and remove insurance record to prevent possible double-spend
delete insurance[i];
}
i++;
}
}
// Called after oracle has updated flight status
function processFlightStatus
(
address airline,
string flight,
uint256 timestamp,
uint8 statusCode,
uint8 multiplyBy,
uint8 divideBy,
uint8 payoutCode
)
public
requireAuthorizedCaller
requireIsOperational
{
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
flights[flightKey].statusCode = statusCode;
if (statusCode == payoutCode) {
creditInsurees(airline, flight, timestamp, multiplyBy, divideBy);
}
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay
(address passenger
)
external
requireAuthorizedCaller
requireIsOperational
{
uint256 amount = passengerCredit[passenger];
passengerCredit[passenger] = 0;
passenger.transfer(amount);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund
(address airlineAddr)
public
payable
requireAuthorizedCaller
requireIsOperational
{
uint256 idx = findAirline(airlineAddr);
if (idx < airlineCount) {
airlines[idx].isFunded = true;
}
}
// Unique hash
function getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
)
pure
internal
returns (bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function()
external
payable
requireAuthorizedCaller
{
// fund();
}
/**
* @dev Returns true if supplied address matches an airline address
*/
function isAirline(address _airline)
public
view
returns (bool)
{
uint256 idx = findAirline(_airline);
if (idx < airlineCount) {
return true;
}
return false;
}
/**
* @dev Returns true if airline is funded
*/
function isFundedAirline(address _airline)
public
view
returns (bool)
{
uint256 idx = findAirline(_airline);
if (idx < airlineCount) {
return airlines[idx].isFunded;
}
// Airline account doesn't exist
return false;
}
// Generate a request for oracles to fetch flight information
function fetchFlightStatus
(
address airline,
string flight,
uint256 timestamp,
address passenderAddr
)
requireAuthorizedCaller
requireIsOperational
external
{
uint8 index = getRandomIndex(passenderAddr);
// Generate a unique key for storing the request
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
oracleResponses[key] = ResponseInfo({
requester : passenderAddr,
isOpen : true
});
emit OracleRequest(index, airline, flight, timestamp);
}
/**
* Total airlines currently registered or waiting to be registered
*/
function getAirlineCount()
public
view
returns (uint256)
{
return airlineCount;
}
// /**
// * Return an array of the airline accounts
// * which need to be extracted from the airlines struct
// */
// function getAirlines()
// external
// view
// returns (address[50])
// {
// address[50] memory acc;
// uint256 i = 0;
// while (i < airlineCount) {
// acc[i] = airlines[i].airlineAccount;
// i++;
// }
// return acc;
// }
// Register an oracle with the contract
function registerOracle
(address oracleAddr
)
external
payable
requireIsOperational
requireAuthorizedCaller
{
uint8[3] memory indexes = generateIndexes(oracleAddr);
Oracle memory newOracle = Oracle({
isRegistered : true,
indexes : indexes
});
oracles[oracleAddr] = newOracle;
}
function getMyIndexes
(address oracleAddr
)
view
public
returns (uint8[3] memory)
{
require(oracles[oracleAddr].isRegistered, "Not registered as an oracle");
return oracles[oracleAddr].indexes;
}
// Called by oracle when a response is available to an outstanding request
// For the response to be accepted, there must be a pending request that is open
// and matches one of the three Indexes randomly assigned to the oracle at the
// time of registration (i.e. uninvited oracles are not welcome)
//
// Multiple/divide numbers provide a method to get percentage amounts of credit
function submitOracleResponse
(
uint8 index,
address airline,
string flight,
uint256 timestamp,
uint8 statusCode,
uint256 min_responses,
address oracleAddr,
uint8 multiplyBy,
uint8 divideBy,
uint8 payoutCode
)
external
requireIsOperational
requireAuthorizedCaller
{
require((oracles[oracleAddr].indexes[0] == index) || (oracles[oracleAddr].indexes[1] == index) || (oracles[oracleAddr].indexes[2] == index), "Index does not match oracle request");
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request");
oracleResponses[key].responses[statusCode].push(oracleAddr);
// Information isn't considered verified until at least MIN_RESPONSES
// oracles respond with the *** same *** information
emit OracleReport(airline, flight, timestamp, statusCode);
if (oracleResponses[key].responses[statusCode].length >= min_responses) {
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
// Handle flight status as appropriate
this.processFlightStatus(airline, flight, timestamp, statusCode, multiplyBy, divideBy, payoutCode);
}
}
// Returns array of three non-duplicating integers from 0-9
function getRandomIndex
(
address account
)
internal
returns (uint8)
{
uint8 maxValue = 10;
// Pseudo random number...the incrementing nonce adds variation
uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number), nonce++, account))) % maxValue);
if (nonce > 250) {
nonce = 0;
// Can only fetch blockhashes for last 256 blocks so we adapt
}
return random;
}
// Returns array of three non-duplicating integers from 0-9
function generateIndexes
(
address account
)
internal
returns (uint8[3] memory)
{
uint8[3] memory indexes;
indexes[0] = getRandomIndex(account);
indexes[1] = indexes[0];
while (indexes[1] == indexes[0]) {
indexes[1] = getRandomIndex(account);
}
indexes[2] = indexes[1];
while ((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) {
indexes[2] = getRandomIndex(account);
}
return indexes;
}
}
| Add a flight schedule to an airline | function registerFlight(address _airline,
string _flight,
uint256 _timestamp)
external
requireIsOperational
requireAuthorizedCaller
{
bytes32 flightKey = getFlightKey(_airline, _flight, _timestamp);
}
| 2,523,537 | [
1,
986,
279,
25187,
4788,
358,
392,
23350,
1369,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1744,
24243,
12,
2867,
389,
1826,
1369,
16,
203,
3639,
533,
389,
19131,
16,
203,
3639,
2254,
5034,
389,
5508,
13,
203,
565,
3903,
203,
565,
2583,
2520,
2988,
287,
203,
565,
2583,
15341,
11095,
203,
565,
288,
203,
3639,
1731,
1578,
25187,
653,
273,
336,
24243,
653,
24899,
1826,
1369,
16,
389,
19131,
16,
389,
5508,
1769,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// File: @openzeppelin/contracts/math/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// 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);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @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: @bancor/token-governance/contracts/IClaimable.sol
pragma solidity 0.6.12;
/// @title Claimable contract interface
interface IClaimable {
function owner() external view returns (address);
function transferOwnership(address newOwner) external;
function acceptOwnership() external;
}
// File: @bancor/token-governance/contracts/IMintableToken.sol
pragma solidity 0.6.12;
/// @title Mintable Token interface
interface IMintableToken is IERC20, IClaimable {
function issue(address to, uint256 amount) external;
function destroy(address from, uint256 amount) external;
}
// File: @bancor/token-governance/contracts/ITokenGovernance.sol
pragma solidity 0.6.12;
/// @title The interface for mintable/burnable token governance.
interface ITokenGovernance {
// The address of the mintable ERC20 token.
function token() external view returns (IMintableToken);
/// @dev Mints new tokens.
///
/// @param to Account to receive the new amount.
/// @param amount Amount to increase the supply by.
///
function mint(address to, uint256 amount) external;
/// @dev Burns tokens from the caller.
///
/// @param amount Amount to decrease the supply by.
///
function burn(uint256 amount) external;
}
// File: solidity/contracts/utility/interfaces/ICheckpointStore.sol
pragma solidity 0.6.12;
/**
* @dev Checkpoint store contract interface
*/
interface ICheckpointStore {
function addCheckpoint(address _address) external;
function addPastCheckpoint(address _address, uint256 _time) external;
function addPastCheckpoints(address[] calldata _addresses, uint256[] calldata _times) external;
function checkpoint(address _address) external view returns (uint256);
}
// File: solidity/contracts/utility/MathEx.sol
pragma solidity 0.6.12;
/**
* @dev This library provides a set of complex math operations.
*/
library MathEx {
uint256 private constant MAX_EXP_BIT_LEN = 4;
uint256 private constant MAX_EXP = 2**MAX_EXP_BIT_LEN - 1;
uint256 private constant MAX_UINT128 = 2**128 - 1;
/**
* @dev returns the largest integer smaller than or equal to the square root of a positive integer
*
* @param _num a positive integer
*
* @return the largest integer smaller than or equal to the square root of the positive integer
*/
function floorSqrt(uint256 _num) internal pure returns (uint256) {
uint256 x = _num / 2 + 1;
uint256 y = (x + _num / x) / 2;
while (x > y) {
x = y;
y = (x + _num / x) / 2;
}
return x;
}
/**
* @dev returns the smallest integer larger than or equal to the square root of a positive integer
*
* @param _num a positive integer
*
* @return the smallest integer larger than or equal to the square root of the positive integer
*/
function ceilSqrt(uint256 _num) internal pure returns (uint256) {
uint256 x = floorSqrt(_num);
return x * x == _num ? x : x + 1;
}
/**
* @dev computes a powered ratio
*
* @param _n ratio numerator
* @param _d ratio denominator
* @param _exp ratio exponent
*
* @return powered ratio's numerator and denominator
*/
function poweredRatio(
uint256 _n,
uint256 _d,
uint256 _exp
) internal pure returns (uint256, uint256) {
require(_exp <= MAX_EXP, "ERR_EXP_TOO_LARGE");
uint256[MAX_EXP_BIT_LEN] memory ns;
uint256[MAX_EXP_BIT_LEN] memory ds;
(ns[0], ds[0]) = reducedRatio(_n, _d, MAX_UINT128);
for (uint256 i = 0; (_exp >> i) > 1; i++) {
(ns[i + 1], ds[i + 1]) = reducedRatio(ns[i] ** 2, ds[i] ** 2, MAX_UINT128);
}
uint256 n = 1;
uint256 d = 1;
for (uint256 i = 0; (_exp >> i) > 0; i++) {
if (((_exp >> i) & 1) > 0) {
(n, d) = reducedRatio(n * ns[i], d * ds[i], MAX_UINT128);
}
}
return (n, d);
}
/**
* @dev computes a reduced-scalar ratio
*
* @param _n ratio numerator
* @param _d ratio denominator
* @param _max maximum desired scalar
*
* @return ratio's numerator and denominator
*/
function reducedRatio(
uint256 _n,
uint256 _d,
uint256 _max
) internal pure returns (uint256, uint256) {
(uint256 n, uint256 d) = (_n, _d);
if (n > _max || d > _max) {
(n, d) = normalizedRatio(n, d, _max);
}
if (n != d) {
return (n, d);
}
return (1, 1);
}
/**
* @dev computes "scale * a / (a + b)" and "scale * b / (a + b)".
*/
function normalizedRatio(
uint256 _a,
uint256 _b,
uint256 _scale
) internal pure returns (uint256, uint256) {
if (_a <= _b) {
return accurateRatio(_a, _b, _scale);
}
(uint256 y, uint256 x) = accurateRatio(_b, _a, _scale);
return (x, y);
}
/**
* @dev computes "scale * a / (a + b)" and "scale * b / (a + b)", assuming that "a <= b".
*/
function accurateRatio(
uint256 _a,
uint256 _b,
uint256 _scale
) internal pure returns (uint256, uint256) {
uint256 maxVal = uint256(-1) / _scale;
if (_a > maxVal) {
uint256 c = _a / (maxVal + 1) + 1;
_a /= c; // we can now safely compute `_a * _scale`
_b /= c;
}
if (_a != _b) {
uint256 n = _a * _scale;
uint256 d = _a + _b; // can overflow
if (d >= _a) {
// no overflow in `_a + _b`
uint256 x = roundDiv(n, d); // we can now safely compute `_scale - x`
uint256 y = _scale - x;
return (x, y);
}
if (n < _b - (_b - _a) / 2) {
return (0, _scale); // `_a * _scale < (_a + _b) / 2 < MAX_UINT256 < _a + _b`
}
return (1, _scale - 1); // `(_a + _b) / 2 < _a * _scale < MAX_UINT256 < _a + _b`
}
return (_scale / 2, _scale / 2); // allow reduction to `(1, 1)` in the calling function
}
/**
* @dev computes the nearest integer to a given quotient without overflowing or underflowing.
*/
function roundDiv(uint256 _n, uint256 _d) internal pure returns (uint256) {
return _n / _d + (_n % _d) / (_d - _d / 2);
}
/**
* @dev returns the average number of decimal digits in a given list of positive integers
*
* @param _values list of positive integers
*
* @return the average number of decimal digits in the given list of positive integers
*/
function geometricMean(uint256[] memory _values) internal pure returns (uint256) {
uint256 numOfDigits = 0;
uint256 length = _values.length;
for (uint256 i = 0; i < length; i++) {
numOfDigits += decimalLength(_values[i]);
}
return uint256(10)**(roundDivUnsafe(numOfDigits, length) - 1);
}
/**
* @dev returns the number of decimal digits in a given positive integer
*
* @param _x positive integer
*
* @return the number of decimal digits in the given positive integer
*/
function decimalLength(uint256 _x) internal pure returns (uint256) {
uint256 y = 0;
for (uint256 x = _x; x > 0; x /= 10) {
y++;
}
return y;
}
/**
* @dev returns the nearest integer to a given quotient
* the computation is overflow-safe assuming that the input is sufficiently small
*
* @param _n quotient numerator
* @param _d quotient denominator
*
* @return the nearest integer to the given quotient
*/
function roundDivUnsafe(uint256 _n, uint256 _d) internal pure returns (uint256) {
return (_n + _d / 2) / _d;
}
/**
* @dev returns the larger of two values
*
* @param _val1 the first value
* @param _val2 the second value
*/
function max(uint256 _val1, uint256 _val2) internal pure returns (uint256) {
return _val1 > _val2 ? _val1 : _val2;
}
}
// File: solidity/contracts/utility/ReentrancyGuard.sol
pragma solidity 0.6.12;
/**
* @dev This contract provides protection against calling a function
* (directly or indirectly) from within itself.
*/
contract ReentrancyGuard {
uint256 private constant UNLOCKED = 1;
uint256 private constant LOCKED = 2;
// LOCKED while protected code is being executed, UNLOCKED otherwise
uint256 private state = UNLOCKED;
/**
* @dev ensures instantiation only by sub-contracts
*/
constructor() internal {}
// protects a function against reentrancy attacks
modifier protected() {
_protected();
state = LOCKED;
_;
state = UNLOCKED;
}
// error message binary size optimization
function _protected() internal view {
require(state == UNLOCKED, "ERR_REENTRANCY");
}
}
// File: solidity/contracts/utility/Types.sol
pragma solidity 0.6.12;
/**
* @dev This contract provides types which can be used by various contracts.
*/
struct Fraction {
uint256 n; // numerator
uint256 d; // denominator
}
// File: solidity/contracts/utility/Time.sol
pragma solidity 0.6.12;
/*
Time implementing contract
*/
contract Time {
/**
* @dev returns the current time
*/
function time() internal view virtual returns (uint256) {
return block.timestamp;
}
}
// File: solidity/contracts/utility/Utils.sol
pragma solidity 0.6.12;
/**
* @dev Utilities & Common Modifiers
*/
contract Utils {
uint32 internal constant PPM_RESOLUTION = 1000000;
// verifies that a value is greater than zero
modifier greaterThanZero(uint256 _value) {
_greaterThanZero(_value);
_;
}
// error message binary size optimization
function _greaterThanZero(uint256 _value) internal pure {
require(_value > 0, "ERR_ZERO_VALUE");
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
_validAddress(_address);
_;
}
// error message binary size optimization
function _validAddress(address _address) internal pure {
require(_address != address(0), "ERR_INVALID_ADDRESS");
}
// ensures that the portion is valid
modifier validPortion(uint32 _portion) {
_validPortion(_portion);
_;
}
// error message binary size optimization
function _validPortion(uint32 _portion) internal pure {
require(_portion > 0 && _portion <= PPM_RESOLUTION, "ERR_INVALID_PORTION");
}
// validates an external address - currently only checks that it isn't null or this
modifier validExternalAddress(address _address) {
_validExternalAddress(_address);
_;
}
// error message binary size optimization
function _validExternalAddress(address _address) internal view {
require(_address != address(0) && _address != address(this), "ERR_INVALID_EXTERNAL_ADDRESS");
}
// ensures that the fee is valid
modifier validFee(uint32 fee) {
_validFee(fee);
_;
}
// error message binary size optimization
function _validFee(uint32 fee) internal pure {
require(fee <= PPM_RESOLUTION, "ERR_INVALID_FEE");
}
}
// File: solidity/contracts/utility/interfaces/IOwned.sol
pragma solidity 0.6.12;
/*
Owned contract interface
*/
interface IOwned {
// this function isn't since the compiler emits automatically generated getter functions as external
function owner() external view returns (address);
function transferOwnership(address _newOwner) external;
function acceptOwnership() external;
}
// File: solidity/contracts/utility/Owned.sol
pragma solidity 0.6.12;
/**
* @dev This contract provides support and utilities for contract ownership.
*/
contract Owned is IOwned {
address public override owner;
address public newOwner;
/**
* @dev triggered when the owner is updated
*
* @param _prevOwner previous owner
* @param _newOwner new owner
*/
event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner);
/**
* @dev initializes a new Owned instance
*/
constructor() public {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
_ownerOnly();
_;
}
// error message binary size optimization
function _ownerOnly() internal view {
require(msg.sender == owner, "ERR_ACCESS_DENIED");
}
/**
* @dev allows transferring the contract ownership
* the new owner still needs to accept the transfer
* can only be called by the contract owner
*
* @param _newOwner new contract owner
*/
function transferOwnership(address _newOwner) public override ownerOnly {
require(_newOwner != owner, "ERR_SAME_OWNER");
newOwner = _newOwner;
}
/**
* @dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() public override {
require(msg.sender == newOwner, "ERR_ACCESS_DENIED");
emit OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// File: solidity/contracts/converter/interfaces/IConverterAnchor.sol
pragma solidity 0.6.12;
/*
Converter Anchor interface
*/
interface IConverterAnchor is IOwned {
}
// File: solidity/contracts/token/interfaces/IDSToken.sol
pragma solidity 0.6.12;
/*
DSToken interface
*/
interface IDSToken is IConverterAnchor, IERC20 {
function issue(address _to, uint256 _amount) external;
function destroy(address _from, uint256 _amount) external;
}
// File: solidity/contracts/token/interfaces/IReserveToken.sol
pragma solidity 0.6.12;
/**
* @dev This contract is used to represent reserve tokens, which are tokens that can either be regular ERC20 tokens or
* native ETH (represented by the NATIVE_TOKEN_ADDRESS address)
*
* Please note that this interface is intentionally doesn't inherit from IERC20, so that it'd be possible to effectively
* override its balanceOf() function in the ReserveToken library
*/
interface IReserveToken {
}
// 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: solidity/contracts/token/SafeERC20Ex.sol
pragma solidity 0.6.12;
/**
* @dev Extends the SafeERC20 library with additional operations
*/
library SafeERC20Ex {
using SafeERC20 for IERC20;
/**
* @dev ensures that the spender has sufficient allowance
*
* @param token the address of the token to ensure
* @param spender the address allowed to spend
* @param amount the allowed amount to spend
*/
function ensureApprove(
IERC20 token,
address spender,
uint256 amount
) internal {
if (amount == 0) {
return;
}
uint256 allowance = token.allowance(address(this), spender);
if (allowance >= amount) {
return;
}
if (allowance > 0) {
token.safeApprove(spender, 0);
}
token.safeApprove(spender, amount);
}
}
// File: solidity/contracts/token/ReserveToken.sol
pragma solidity 0.6.12;
/**
* @dev This library implements ERC20 and SafeERC20 utilities for reserve tokens, which can be either ERC20 tokens or ETH
*/
library ReserveToken {
using SafeERC20 for IERC20;
using SafeERC20Ex for IERC20;
// the address that represents an ETH reserve
IReserveToken public constant NATIVE_TOKEN_ADDRESS = IReserveToken(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
/**
* @dev returns whether the provided token represents an ERC20 or ETH reserve
*
* @param reserveToken the address of the reserve token
*
* @return whether the provided token represents an ERC20 or ETH reserve
*/
function isNativeToken(IReserveToken reserveToken) internal pure returns (bool) {
return reserveToken == NATIVE_TOKEN_ADDRESS;
}
/**
* @dev returns the balance of the reserve token
*
* @param reserveToken the address of the reserve token
* @param account the address of the account to check
*
* @return the balance of the reserve token
*/
function balanceOf(IReserveToken reserveToken, address account) internal view returns (uint256) {
if (isNativeToken(reserveToken)) {
return account.balance;
}
return toIERC20(reserveToken).balanceOf(account);
}
/**
* @dev transfers a specific amount of the reserve token
*
* @param reserveToken the address of the reserve token
* @param to the destination address to transfer the amount to
* @param amount the amount to transfer
*/
function safeTransfer(
IReserveToken reserveToken,
address to,
uint256 amount
) internal {
if (amount == 0) {
return;
}
if (isNativeToken(reserveToken)) {
payable(to).transfer(amount);
} else {
toIERC20(reserveToken).safeTransfer(to, amount);
}
}
/**
* @dev transfers a specific amount of the reserve token from a specific holder using the allowance mechanism
* this function ignores a reserve token which represents an ETH reserve
*
* @param reserveToken the address of the reserve token
* @param from the source address to transfer the amount from
* @param to the destination address to transfer the amount to
* @param amount the amount to transfer
*/
function safeTransferFrom(
IReserveToken reserveToken,
address from,
address to,
uint256 amount
) internal {
if (amount == 0 || isNativeToken(reserveToken)) {
return;
}
toIERC20(reserveToken).safeTransferFrom(from, to, amount);
}
/**
* @dev ensures that the spender has sufficient allowance
* this function ignores a reserve token which represents an ETH reserve
*
* @param reserveToken the address of the reserve token
* @param spender the address allowed to spend
* @param amount the allowed amount to spend
*/
function ensureApprove(
IReserveToken reserveToken,
address spender,
uint256 amount
) internal {
if (isNativeToken(reserveToken)) {
return;
}
toIERC20(reserveToken).ensureApprove(spender, amount);
}
/**
* @dev utility function that converts an IReserveToken to an IERC20
*
* @param reserveToken the address of the reserve token
*
* @return an IERC20
*/
function toIERC20(IReserveToken reserveToken) private pure returns (IERC20) {
return IERC20(address(reserveToken));
}
}
// File: solidity/contracts/converter/interfaces/IConverter.sol
pragma solidity 0.6.12;
/*
Converter interface
*/
interface IConverter is IOwned {
function converterType() external pure returns (uint16);
function anchor() external view returns (IConverterAnchor);
function isActive() external view returns (bool);
function targetAmountAndFee(
IReserveToken _sourceToken,
IReserveToken _targetToken,
uint256 _amount
) external view returns (uint256, uint256);
function convert(
IReserveToken _sourceToken,
IReserveToken _targetToken,
uint256 _amount,
address _trader,
address payable _beneficiary
) external payable returns (uint256);
function conversionFee() external view returns (uint32);
function maxConversionFee() external view returns (uint32);
function reserveBalance(IReserveToken _reserveToken) external view returns (uint256);
receive() external payable;
function transferAnchorOwnership(address _newOwner) external;
function acceptAnchorOwnership() external;
function setConversionFee(uint32 _conversionFee) external;
function addReserve(IReserveToken _token, uint32 _weight) external;
function transferReservesOnUpgrade(address _newConverter) external;
function onUpgradeComplete() external;
// deprecated, backward compatibility
function token() external view returns (IConverterAnchor);
function transferTokenOwnership(address _newOwner) external;
function acceptTokenOwnership() external;
function connectors(IReserveToken _address)
external
view
returns (
uint256,
uint32,
bool,
bool,
bool
);
function getConnectorBalance(IReserveToken _connectorToken) external view returns (uint256);
function connectorTokens(uint256 _index) external view returns (IReserveToken);
function connectorTokenCount() external view returns (uint16);
/**
* @dev triggered when the converter is activated
*
* @param _type converter type
* @param _anchor converter anchor
* @param _activated true if the converter was activated, false if it was deactivated
*/
event Activation(uint16 indexed _type, IConverterAnchor indexed _anchor, bool indexed _activated);
/**
* @dev triggered when a conversion between two tokens occurs
*
* @param _fromToken source reserve token
* @param _toToken target reserve token
* @param _trader wallet that initiated the trade
* @param _amount input amount in units of the source token
* @param _return output amount minus conversion fee in units of the target token
* @param _conversionFee conversion fee in units of the target token
*/
event Conversion(
IReserveToken indexed _fromToken,
IReserveToken indexed _toToken,
address indexed _trader,
uint256 _amount,
uint256 _return,
int256 _conversionFee
);
/**
* @dev triggered when the rate between two tokens in the converter changes
* note that the event might be dispatched for rate updates between any two tokens in the converter
*
* @param _token1 address of the first token
* @param _token2 address of the second token
* @param _rateN rate of 1 unit of `_token1` in `_token2` (numerator)
* @param _rateD rate of 1 unit of `_token1` in `_token2` (denominator)
*/
event TokenRateUpdate(address indexed _token1, address indexed _token2, uint256 _rateN, uint256 _rateD);
/**
* @dev triggered when the conversion fee is updated
*
* @param _prevFee previous fee percentage, represented in ppm
* @param _newFee new fee percentage, represented in ppm
*/
event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee);
}
// File: solidity/contracts/converter/interfaces/IConverterRegistry.sol
pragma solidity 0.6.12;
interface IConverterRegistry {
function getAnchorCount() external view returns (uint256);
function getAnchors() external view returns (address[] memory);
function getAnchor(uint256 _index) external view returns (IConverterAnchor);
function isAnchor(address _value) external view returns (bool);
function getLiquidityPoolCount() external view returns (uint256);
function getLiquidityPools() external view returns (address[] memory);
function getLiquidityPool(uint256 _index) external view returns (IConverterAnchor);
function isLiquidityPool(address _value) external view returns (bool);
function getConvertibleTokenCount() external view returns (uint256);
function getConvertibleTokens() external view returns (address[] memory);
function getConvertibleToken(uint256 _index) external view returns (IReserveToken);
function isConvertibleToken(address _value) external view returns (bool);
function getConvertibleTokenAnchorCount(IReserveToken _convertibleToken) external view returns (uint256);
function getConvertibleTokenAnchors(IReserveToken _convertibleToken) external view returns (address[] memory);
function getConvertibleTokenAnchor(IReserveToken _convertibleToken, uint256 _index)
external
view
returns (IConverterAnchor);
function isConvertibleTokenAnchor(IReserveToken _convertibleToken, address _value) external view returns (bool);
function getLiquidityPoolByConfig(
uint16 _type,
IReserveToken[] memory _reserveTokens,
uint32[] memory _reserveWeights
) external view returns (IConverterAnchor);
}
// File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionStore.sol
pragma solidity 0.6.12;
/*
Liquidity Protection Store interface
*/
interface ILiquidityProtectionStore is IOwned {
function withdrawTokens(
IReserveToken _token,
address _to,
uint256 _amount
) external;
function protectedLiquidity(uint256 _id)
external
view
returns (
address,
IDSToken,
IReserveToken,
uint256,
uint256,
uint256,
uint256,
uint256
);
function addProtectedLiquidity(
address _provider,
IDSToken _poolToken,
IReserveToken _reserveToken,
uint256 _poolAmount,
uint256 _reserveAmount,
uint256 _reserveRateN,
uint256 _reserveRateD,
uint256 _timestamp
) external returns (uint256);
function updateProtectedLiquidityAmounts(
uint256 _id,
uint256 _poolNewAmount,
uint256 _reserveNewAmount
) external;
function removeProtectedLiquidity(uint256 _id) external;
function lockedBalance(address _provider, uint256 _index) external view returns (uint256, uint256);
function lockedBalanceRange(
address _provider,
uint256 _startIndex,
uint256 _endIndex
) external view returns (uint256[] memory, uint256[] memory);
function addLockedBalance(
address _provider,
uint256 _reserveAmount,
uint256 _expirationTime
) external returns (uint256);
function removeLockedBalance(address _provider, uint256 _index) external;
function systemBalance(IReserveToken _poolToken) external view returns (uint256);
function incSystemBalance(IReserveToken _poolToken, uint256 _poolAmount) external;
function decSystemBalance(IReserveToken _poolToken, uint256 _poolAmount) external;
}
// File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionStats.sol
pragma solidity 0.6.12;
/*
Liquidity Protection Stats interface
*/
interface ILiquidityProtectionStats {
function increaseTotalAmounts(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
uint256 poolAmount,
uint256 reserveAmount
) external;
function decreaseTotalAmounts(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
uint256 poolAmount,
uint256 reserveAmount
) external;
function addProviderPool(address provider, IDSToken poolToken) external returns (bool);
function removeProviderPool(address provider, IDSToken poolToken) external returns (bool);
function totalPoolAmount(IDSToken poolToken) external view returns (uint256);
function totalReserveAmount(IDSToken poolToken, IReserveToken reserveToken) external view returns (uint256);
function totalProviderAmount(
address provider,
IDSToken poolToken,
IReserveToken reserveToken
) external view returns (uint256);
function providerPools(address provider) external view returns (IDSToken[] memory);
}
// File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProvisionEventsSubscriber.sol
pragma solidity 0.6.12;
/**
* @dev Liquidity provision events subscriber interface
*/
interface ILiquidityProvisionEventsSubscriber {
function onAddingLiquidity(
address provider,
IConverterAnchor poolAnchor,
IReserveToken reserveToken,
uint256 poolAmount,
uint256 reserveAmount
) external;
function onRemovingLiquidity(
uint256 id,
address provider,
IConverterAnchor poolAnchor,
IReserveToken reserveToken,
uint256 poolAmount,
uint256 reserveAmount
) external;
}
// File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionSettings.sol
pragma solidity 0.6.12;
/*
Liquidity Protection Store Settings interface
*/
interface ILiquidityProtectionSettings {
function isPoolWhitelisted(IConverterAnchor poolAnchor) external view returns (bool);
function poolWhitelist() external view returns (address[] memory);
function subscribers() external view returns (address[] memory);
function isPoolSupported(IConverterAnchor poolAnchor) external view returns (bool);
function minNetworkTokenLiquidityForMinting() external view returns (uint256);
function defaultNetworkTokenMintingLimit() external view returns (uint256);
function networkTokenMintingLimits(IConverterAnchor poolAnchor) external view returns (uint256);
function addLiquidityDisabled(IConverterAnchor poolAnchor, IReserveToken reserveToken) external view returns (bool);
function minProtectionDelay() external view returns (uint256);
function maxProtectionDelay() external view returns (uint256);
function minNetworkCompensation() external view returns (uint256);
function lockDuration() external view returns (uint256);
function averageRateMaxDeviation() external view returns (uint32);
}
// File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionSystemStore.sol
pragma solidity 0.6.12;
/*
Liquidity Protection System Store interface
*/
interface ILiquidityProtectionSystemStore {
function systemBalance(IERC20 poolToken) external view returns (uint256);
function incSystemBalance(IERC20 poolToken, uint256 poolAmount) external;
function decSystemBalance(IERC20 poolToken, uint256 poolAmount) external;
function networkTokensMinted(IConverterAnchor poolAnchor) external view returns (uint256);
function incNetworkTokensMinted(IConverterAnchor poolAnchor, uint256 amount) external;
function decNetworkTokensMinted(IConverterAnchor poolAnchor, uint256 amount) external;
}
// File: solidity/contracts/liquidity-protection/interfaces/ITransferPositionCallback.sol
pragma solidity 0.6.12;
/**
* @dev Transfer position event callback interface
*/
interface ITransferPositionCallback {
function onTransferPosition(
uint256 newId,
address provider,
bytes calldata data
) external;
}
// File: solidity/contracts/utility/interfaces/ITokenHolder.sol
pragma solidity 0.6.12;
/*
Token Holder interface
*/
interface ITokenHolder is IOwned {
receive() external payable;
function withdrawTokens(
IReserveToken reserveToken,
address payable to,
uint256 amount
) external;
function withdrawTokensMultiple(
IReserveToken[] calldata reserveTokens,
address payable to,
uint256[] calldata amounts
) external;
}
// File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtection.sol
pragma solidity 0.6.12;
/*
Liquidity Protection interface
*/
interface ILiquidityProtection {
function store() external view returns (ILiquidityProtectionStore);
function stats() external view returns (ILiquidityProtectionStats);
function settings() external view returns (ILiquidityProtectionSettings);
function systemStore() external view returns (ILiquidityProtectionSystemStore);
function wallet() external view returns (ITokenHolder);
function addLiquidityFor(
address owner,
IConverterAnchor poolAnchor,
IReserveToken reserveToken,
uint256 amount
) external payable returns (uint256);
function addLiquidity(
IConverterAnchor poolAnchor,
IReserveToken reserveToken,
uint256 amount
) external payable returns (uint256);
function removeLiquidity(uint256 id, uint32 portion) external;
function transferPosition(uint256 id, address newProvider) external returns (uint256);
function transferPositionAndNotify(
uint256 id,
address newProvider,
ITransferPositionCallback callback,
bytes calldata data
) external returns (uint256);
}
// File: solidity/contracts/liquidity-protection/LiquidityProtection.sol
pragma solidity 0.6.12;
interface ILiquidityPoolConverter is IConverter {
function addLiquidity(
IReserveToken[] memory reserveTokens,
uint256[] memory reserveAmounts,
uint256 _minReturn
) external payable;
function removeLiquidity(
uint256 amount,
IReserveToken[] memory reserveTokens,
uint256[] memory _reserveMinReturnAmounts
) external;
function recentAverageRate(IReserveToken reserveToken) external view returns (uint256, uint256);
}
/**
* @dev This contract implements the liquidity protection mechanism.
*/
contract LiquidityProtection is ILiquidityProtection, Utils, Owned, ReentrancyGuard, Time {
using SafeMath for uint256;
using ReserveToken for IReserveToken;
using SafeERC20 for IERC20;
using SafeERC20 for IDSToken;
using SafeERC20Ex for IERC20;
using MathEx for *;
struct Position {
address provider; // liquidity provider
IDSToken poolToken; // pool token address
IReserveToken reserveToken; // reserve token address
uint256 poolAmount; // pool token amount
uint256 reserveAmount; // reserve token amount
uint256 reserveRateN; // rate of 1 protected reserve token in units of the other reserve token (numerator)
uint256 reserveRateD; // rate of 1 protected reserve token in units of the other reserve token (denominator)
uint256 timestamp; // timestamp
}
// various rates between the two reserve tokens. the rate is of 1 unit of the protected reserve token in units of the other reserve token
struct PackedRates {
uint128 addSpotRateN; // spot rate of 1 A in units of B when liquidity was added (numerator)
uint128 addSpotRateD; // spot rate of 1 A in units of B when liquidity was added (denominator)
uint128 removeSpotRateN; // spot rate of 1 A in units of B when liquidity is removed (numerator)
uint128 removeSpotRateD; // spot rate of 1 A in units of B when liquidity is removed (denominator)
uint128 removeAverageRateN; // average rate of 1 A in units of B when liquidity is removed (numerator)
uint128 removeAverageRateD; // average rate of 1 A in units of B when liquidity is removed (denominator)
}
uint256 internal constant MAX_UINT128 = 2**128 - 1;
uint256 internal constant MAX_UINT256 = uint256(-1);
ILiquidityProtectionSettings private immutable _settings;
ILiquidityProtectionStore private immutable _store;
ILiquidityProtectionStats private immutable _stats;
ILiquidityProtectionSystemStore private immutable _systemStore;
ITokenHolder private immutable _wallet;
IERC20 private immutable _networkToken;
ITokenGovernance private immutable _networkTokenGovernance;
IERC20 private immutable _govToken;
ITokenGovernance private immutable _govTokenGovernance;
ICheckpointStore private immutable _lastRemoveCheckpointStore;
/**
* @dev initializes a new LiquidityProtection contract
*
* @param settings liquidity protection settings
* @param store liquidity protection store
* @param stats liquidity protection stats
* @param systemStore liquidity protection system store
* @param wallet liquidity protection wallet
* @param networkTokenGovernance network token governance
* @param govTokenGovernance governance token governance
* @param lastRemoveCheckpointStore last liquidity removal/unprotection checkpoints store
*/
constructor(
ILiquidityProtectionSettings settings,
ILiquidityProtectionStore store,
ILiquidityProtectionStats stats,
ILiquidityProtectionSystemStore systemStore,
ITokenHolder wallet,
ITokenGovernance networkTokenGovernance,
ITokenGovernance govTokenGovernance,
ICheckpointStore lastRemoveCheckpointStore
)
public
validAddress(address(settings))
validAddress(address(store))
validAddress(address(stats))
validAddress(address(systemStore))
validAddress(address(wallet))
validAddress(address(lastRemoveCheckpointStore))
{
_settings = settings;
_store = store;
_stats = stats;
_systemStore = systemStore;
_wallet = wallet;
_networkTokenGovernance = networkTokenGovernance;
_govTokenGovernance = govTokenGovernance;
_lastRemoveCheckpointStore = lastRemoveCheckpointStore;
_networkToken = networkTokenGovernance.token();
_govToken = govTokenGovernance.token();
}
// ensures that the pool is supported and whitelisted
modifier poolSupportedAndWhitelisted(IConverterAnchor poolAnchor) {
_poolSupported(poolAnchor);
_poolWhitelisted(poolAnchor);
_;
}
// ensures that add liquidity is enabled
modifier addLiquidityEnabled(IConverterAnchor poolAnchor, IReserveToken reserveToken) {
_addLiquidityEnabled(poolAnchor, reserveToken);
_;
}
// error message binary size optimization
function _poolSupported(IConverterAnchor poolAnchor) internal view {
require(_settings.isPoolSupported(poolAnchor), "ERR_POOL_NOT_SUPPORTED");
}
// error message binary size optimization
function _poolWhitelisted(IConverterAnchor poolAnchor) internal view {
require(_settings.isPoolWhitelisted(poolAnchor), "ERR_POOL_NOT_WHITELISTED");
}
// error message binary size optimization
function _addLiquidityEnabled(IConverterAnchor poolAnchor, IReserveToken reserveToken) internal view {
require(!_settings.addLiquidityDisabled(poolAnchor, reserveToken), "ERR_ADD_LIQUIDITY_DISABLED");
}
// error message binary size optimization
function verifyEthAmount(uint256 value) internal view {
require(msg.value == value, "ERR_ETH_AMOUNT_MISMATCH");
}
/**
* @dev returns the LP store
*
* @return the LP store
*/
function store() external view override returns (ILiquidityProtectionStore) {
return _store;
}
/**
* @dev returns the LP stats
*
* @return the LP stats
*/
function stats() external view override returns (ILiquidityProtectionStats) {
return _stats;
}
/**
* @dev returns the LP settings
*
* @return the LP settings
*/
function settings() external view override returns (ILiquidityProtectionSettings) {
return _settings;
}
/**
* @dev returns the LP system store
*
* @return the LP system store
*/
function systemStore() external view override returns (ILiquidityProtectionSystemStore) {
return _systemStore;
}
/**
* @dev returns the LP wallet
*
* @return the LP wallet
*/
function wallet() external view override returns (ITokenHolder) {
return _wallet;
}
/**
* @dev accept ETH
*/
receive() external payable {}
/**
* @dev transfers the ownership of the store
* can only be called by the contract owner
*
* @param newOwner the new owner of the store
*/
function transferStoreOwnership(address newOwner) external ownerOnly {
_store.transferOwnership(newOwner);
}
/**
* @dev accepts the ownership of the store
* can only be called by the contract owner
*/
function acceptStoreOwnership() external ownerOnly {
_store.acceptOwnership();
}
/**
* @dev transfers the ownership of the wallet
* can only be called by the contract owner
*
* @param newOwner the new owner of the wallet
*/
function transferWalletOwnership(address newOwner) external ownerOnly {
_wallet.transferOwnership(newOwner);
}
/**
* @dev accepts the ownership of the wallet
* can only be called by the contract owner
*/
function acceptWalletOwnership() external ownerOnly {
_wallet.acceptOwnership();
}
/**
* @dev adds protected liquidity to a pool for a specific recipient
* also mints new governance tokens for the caller if the caller adds network tokens
*
* @param owner position owner
* @param poolAnchor anchor of the pool
* @param reserveToken reserve token to add to the pool
* @param amount amount of tokens to add to the pool
*
* @return new position id
*/
function addLiquidityFor(
address owner,
IConverterAnchor poolAnchor,
IReserveToken reserveToken,
uint256 amount
)
external
payable
override
protected
validAddress(owner)
poolSupportedAndWhitelisted(poolAnchor)
addLiquidityEnabled(poolAnchor, reserveToken)
greaterThanZero(amount)
returns (uint256)
{
return addLiquidity(owner, poolAnchor, reserveToken, amount);
}
/**
* @dev adds protected liquidity to a pool
* also mints new governance tokens for the caller if the caller adds network tokens
*
* @param poolAnchor anchor of the pool
* @param reserveToken reserve token to add to the pool
* @param amount amount of tokens to add to the pool
*
* @return new position id
*/
function addLiquidity(
IConverterAnchor poolAnchor,
IReserveToken reserveToken,
uint256 amount
)
external
payable
override
protected
poolSupportedAndWhitelisted(poolAnchor)
addLiquidityEnabled(poolAnchor, reserveToken)
greaterThanZero(amount)
returns (uint256)
{
return addLiquidity(msg.sender, poolAnchor, reserveToken, amount);
}
/**
* @dev adds protected liquidity to a pool for a specific recipient
* also mints new governance tokens for the caller if the caller adds network tokens
*
* @param owner position owner
* @param poolAnchor anchor of the pool
* @param reserveToken reserve token to add to the pool
* @param amount amount of tokens to add to the pool
*
* @return new position id
*/
function addLiquidity(
address owner,
IConverterAnchor poolAnchor,
IReserveToken reserveToken,
uint256 amount
) private returns (uint256) {
if (isNetworkToken(reserveToken)) {
verifyEthAmount(0);
return addNetworkTokenLiquidity(owner, poolAnchor, amount);
}
// verify that ETH was passed with the call if needed
verifyEthAmount(reserveToken.isNativeToken() ? amount : 0);
return addBaseTokenLiquidity(owner, poolAnchor, reserveToken, amount);
}
/**
* @dev adds network token liquidity to a pool
* also mints new governance tokens for the caller
*
* @param owner position owner
* @param poolAnchor anchor of the pool
* @param amount amount of tokens to add to the pool
*
* @return new position id
*/
function addNetworkTokenLiquidity(
address owner,
IConverterAnchor poolAnchor,
uint256 amount
) internal returns (uint256) {
IDSToken poolToken = IDSToken(address(poolAnchor));
IReserveToken networkToken = IReserveToken(address(_networkToken));
// get the rate between the pool token and the reserve
Fraction memory poolRate = poolTokenRate(poolToken, networkToken);
// calculate the amount of pool tokens based on the amount of reserve tokens
uint256 poolTokenAmount = amount.mul(poolRate.d).div(poolRate.n);
// remove the pool tokens from the system's ownership (will revert if not enough tokens are available)
_systemStore.decSystemBalance(poolToken, poolTokenAmount);
// add the position for the recipient
uint256 id = addPosition(owner, poolToken, networkToken, poolTokenAmount, amount, time());
// burns the network tokens from the caller. we need to transfer the tokens to the contract itself, since only
// token holders can burn their tokens
_networkToken.safeTransferFrom(msg.sender, address(this), amount);
burnNetworkTokens(poolAnchor, amount);
// mint governance tokens to the recipient
_govTokenGovernance.mint(owner, amount);
return id;
}
/**
* @dev adds base token liquidity to a pool
*
* @param owner position owner
* @param poolAnchor anchor of the pool
* @param baseToken the base reserve token of the pool
* @param amount amount of tokens to add to the pool
*
* @return new position id
*/
function addBaseTokenLiquidity(
address owner,
IConverterAnchor poolAnchor,
IReserveToken baseToken,
uint256 amount
) internal returns (uint256) {
IDSToken poolToken = IDSToken(address(poolAnchor));
IReserveToken networkToken = IReserveToken(address(_networkToken));
// get the reserve balances
ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(poolAnchor)));
(uint256 reserveBalanceBase, uint256 reserveBalanceNetwork) =
converterReserveBalances(converter, baseToken, networkToken);
require(reserveBalanceNetwork >= _settings.minNetworkTokenLiquidityForMinting(), "ERR_NOT_ENOUGH_LIQUIDITY");
// calculate and mint the required amount of network tokens for adding liquidity
uint256 newNetworkLiquidityAmount = amount.mul(reserveBalanceNetwork).div(reserveBalanceBase);
// verify network token minting limit
uint256 mintingLimit = _settings.networkTokenMintingLimits(poolAnchor);
if (mintingLimit == 0) {
mintingLimit = _settings.defaultNetworkTokenMintingLimit();
}
uint256 newNetworkTokensMinted = _systemStore.networkTokensMinted(poolAnchor).add(newNetworkLiquidityAmount);
require(newNetworkTokensMinted <= mintingLimit, "ERR_MAX_AMOUNT_REACHED");
// issue new network tokens to the system
mintNetworkTokens(address(this), poolAnchor, newNetworkLiquidityAmount);
// transfer the base tokens from the caller and approve the converter
networkToken.ensureApprove(address(converter), newNetworkLiquidityAmount);
if (!baseToken.isNativeToken()) {
baseToken.safeTransferFrom(msg.sender, address(this), amount);
baseToken.ensureApprove(address(converter), amount);
}
// add the liquidity to the converter
addLiquidity(converter, baseToken, networkToken, amount, newNetworkLiquidityAmount, msg.value);
// transfer the new pool tokens to the wallet
uint256 poolTokenAmount = poolToken.balanceOf(address(this));
poolToken.safeTransfer(address(_wallet), poolTokenAmount);
// the system splits the pool tokens with the caller
// increase the system's pool token balance and add the position for the caller
_systemStore.incSystemBalance(poolToken, poolTokenAmount - poolTokenAmount / 2); // account for rounding errors
return addPosition(owner, poolToken, baseToken, poolTokenAmount / 2, amount, time());
}
/**
* @dev returns the single-side staking limits of a given pool
*
* @param poolAnchor anchor of the pool
*
* @return maximum amount of base tokens that can be single-side staked in the pool
* @return maximum amount of network tokens that can be single-side staked in the pool
*/
function poolAvailableSpace(IConverterAnchor poolAnchor)
external
view
poolSupportedAndWhitelisted(poolAnchor)
returns (uint256, uint256)
{
return (baseTokenAvailableSpace(poolAnchor), networkTokenAvailableSpace(poolAnchor));
}
/**
* @dev returns the base-token staking limits of a given pool
*
* @param poolAnchor anchor of the pool
*
* @return maximum amount of base tokens that can be single-side staked in the pool
*/
function baseTokenAvailableSpace(IConverterAnchor poolAnchor) internal view returns (uint256) {
// get the pool converter
ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(poolAnchor)));
// get the base token
IReserveToken networkToken = IReserveToken(address(_networkToken));
IReserveToken baseToken = converterOtherReserve(converter, networkToken);
// get the reserve balances
(uint256 reserveBalanceBase, uint256 reserveBalanceNetwork) =
converterReserveBalances(converter, baseToken, networkToken);
// get the network token minting limit
uint256 mintingLimit = _settings.networkTokenMintingLimits(poolAnchor);
if (mintingLimit == 0) {
mintingLimit = _settings.defaultNetworkTokenMintingLimit();
}
// get the amount of network tokens already minted for the pool
uint256 networkTokensMinted = _systemStore.networkTokensMinted(poolAnchor);
// get the amount of network tokens which can minted for the pool
uint256 networkTokensCanBeMinted = MathEx.max(mintingLimit, networkTokensMinted) - networkTokensMinted;
// return the maximum amount of base token liquidity that can be single-sided staked in the pool
return networkTokensCanBeMinted.mul(reserveBalanceBase).div(reserveBalanceNetwork);
}
/**
* @dev returns the network-token staking limits of a given pool
*
* @param poolAnchor anchor of the pool
*
* @return maximum amount of network tokens that can be single-side staked in the pool
*/
function networkTokenAvailableSpace(IConverterAnchor poolAnchor) internal view returns (uint256) {
// get the pool token
IDSToken poolToken = IDSToken(address(poolAnchor));
IReserveToken networkToken = IReserveToken(address(_networkToken));
// get the pool token rate
Fraction memory poolRate = poolTokenRate(poolToken, networkToken);
// return the maximum amount of network token liquidity that can be single-sided staked in the pool
return _systemStore.systemBalance(poolToken).mul(poolRate.n).add(poolRate.n).sub(1).div(poolRate.d);
}
/**
* @dev returns the expected/actual amounts the provider will receive for removing liquidity
* it's also possible to provide the remove liquidity time to get an estimation
* for the return at that given point
*
* @param id position id
* @param portion portion of liquidity to remove, in PPM
* @param removeTimestamp time at which the liquidity is removed
*
* @return expected return amount in the reserve token
* @return actual return amount in the reserve token
* @return compensation in the network token
*/
function removeLiquidityReturn(
uint256 id,
uint32 portion,
uint256 removeTimestamp
)
external
view
validPortion(portion)
returns (
uint256,
uint256,
uint256
)
{
Position memory pos = position(id);
// verify input
require(pos.provider != address(0), "ERR_INVALID_ID");
require(removeTimestamp >= pos.timestamp, "ERR_INVALID_TIMESTAMP");
// calculate the portion of the liquidity to remove
if (portion != PPM_RESOLUTION) {
pos.poolAmount = pos.poolAmount.mul(portion) / PPM_RESOLUTION;
pos.reserveAmount = pos.reserveAmount.mul(portion) / PPM_RESOLUTION;
}
// get the various rates between the reserves upon adding liquidity and now
PackedRates memory packedRates = packRates(pos.poolToken, pos.reserveToken, pos.reserveRateN, pos.reserveRateD);
uint256 targetAmount =
removeLiquidityTargetAmount(
pos.poolToken,
pos.reserveToken,
pos.poolAmount,
pos.reserveAmount,
packedRates,
pos.timestamp,
removeTimestamp
);
// for network token, the return amount is identical to the target amount
if (isNetworkToken(pos.reserveToken)) {
return (targetAmount, targetAmount, 0);
}
// handle base token return
// calculate the amount of pool tokens required for liquidation
// note that the amount is doubled since it's not possible to liquidate one reserve only
Fraction memory poolRate = poolTokenRate(pos.poolToken, pos.reserveToken);
uint256 poolAmount = targetAmount.mul(poolRate.d).div(poolRate.n / 2);
// limit the amount of pool tokens by the amount the system/caller holds
uint256 availableBalance = _systemStore.systemBalance(pos.poolToken).add(pos.poolAmount);
poolAmount = poolAmount > availableBalance ? availableBalance : poolAmount;
// calculate the base token amount received by liquidating the pool tokens
// note that the amount is divided by 2 since the pool amount represents both reserves
uint256 baseAmount = poolAmount.mul(poolRate.n / 2).div(poolRate.d);
uint256 networkAmount = networkCompensation(targetAmount, baseAmount, packedRates);
return (targetAmount, baseAmount, networkAmount);
}
/**
* @dev removes protected liquidity from a pool
* also burns governance tokens from the caller if the caller removes network tokens
*
* @param id position id
* @param portion portion of liquidity to remove, in PPM
*/
function removeLiquidity(uint256 id, uint32 portion) external override protected validPortion(portion) {
removeLiquidity(msg.sender, id, portion);
}
/**
* @dev removes a position from a pool
* also burns governance tokens from the caller if the caller removes network tokens
*
* @param provider liquidity provider
* @param id position id
* @param portion portion of liquidity to remove, in PPM
*/
function removeLiquidity(
address payable provider,
uint256 id,
uint32 portion
) internal {
// remove the position from the store and update the stats and the last removal checkpoint
Position memory removedPos = removePosition(provider, id, portion);
// add the pool tokens to the system
_systemStore.incSystemBalance(removedPos.poolToken, removedPos.poolAmount);
// if removing network token liquidity, burn the governance tokens from the caller. we need to transfer the
// tokens to the contract itself, since only token holders can burn their tokens
if (isNetworkToken(removedPos.reserveToken)) {
_govToken.safeTransferFrom(provider, address(this), removedPos.reserveAmount);
_govTokenGovernance.burn(removedPos.reserveAmount);
}
// get the various rates between the reserves upon adding liquidity and now
PackedRates memory packedRates =
packRates(removedPos.poolToken, removedPos.reserveToken, removedPos.reserveRateN, removedPos.reserveRateD);
// verify rate deviation as early as possible in order to reduce gas-cost for failing transactions
verifyRateDeviation(
packedRates.removeSpotRateN,
packedRates.removeSpotRateD,
packedRates.removeAverageRateN,
packedRates.removeAverageRateD
);
// get the target token amount
uint256 targetAmount =
removeLiquidityTargetAmount(
removedPos.poolToken,
removedPos.reserveToken,
removedPos.poolAmount,
removedPos.reserveAmount,
packedRates,
removedPos.timestamp,
time()
);
// remove network token liquidity
if (isNetworkToken(removedPos.reserveToken)) {
// mint network tokens for the caller and lock them
mintNetworkTokens(address(_wallet), removedPos.poolToken, targetAmount);
lockTokens(provider, targetAmount);
return;
}
// remove base token liquidity
// calculate the amount of pool tokens required for liquidation
// note that the amount is doubled since it's not possible to liquidate one reserve only
Fraction memory poolRate = poolTokenRate(removedPos.poolToken, removedPos.reserveToken);
uint256 poolAmount = targetAmount.mul(poolRate.d).div(poolRate.n / 2);
// limit the amount of pool tokens by the amount the system holds
uint256 systemBalance = _systemStore.systemBalance(removedPos.poolToken);
poolAmount = poolAmount > systemBalance ? systemBalance : poolAmount;
// withdraw the pool tokens from the wallet
IReserveToken poolToken = IReserveToken(address(removedPos.poolToken));
_systemStore.decSystemBalance(removedPos.poolToken, poolAmount);
_wallet.withdrawTokens(poolToken, address(this), poolAmount);
// remove liquidity
removeLiquidity(
removedPos.poolToken,
poolAmount,
removedPos.reserveToken,
IReserveToken(address(_networkToken))
);
// transfer the base tokens to the caller
uint256 baseBalance = removedPos.reserveToken.balanceOf(address(this));
removedPos.reserveToken.safeTransfer(provider, baseBalance);
// compensate the caller with network tokens if still needed
uint256 delta = networkCompensation(targetAmount, baseBalance, packedRates);
if (delta > 0) {
// check if there's enough network token balance, otherwise mint more
uint256 networkBalance = _networkToken.balanceOf(address(this));
if (networkBalance < delta) {
_networkTokenGovernance.mint(address(this), delta - networkBalance);
}
// lock network tokens for the caller
_networkToken.safeTransfer(address(_wallet), delta);
lockTokens(provider, delta);
}
// if the contract still holds network tokens, burn them
uint256 networkBalance = _networkToken.balanceOf(address(this));
if (networkBalance > 0) {
burnNetworkTokens(removedPos.poolToken, networkBalance);
}
}
/**
* @dev returns the amount the provider will receive for removing liquidity
* it's also possible to provide the remove liquidity rate & time to get an estimation
* for the return at that given point
*
* @param poolToken pool token
* @param reserveToken reserve token
* @param poolAmount pool token amount when the liquidity was added
* @param reserveAmount reserve token amount that was added
* @param packedRates see `struct PackedRates`
* @param addTimestamp time at which the liquidity was added
* @param removeTimestamp time at which the liquidity is removed
*
* @return amount received for removing liquidity
*/
function removeLiquidityTargetAmount(
IDSToken poolToken,
IReserveToken reserveToken,
uint256 poolAmount,
uint256 reserveAmount,
PackedRates memory packedRates,
uint256 addTimestamp,
uint256 removeTimestamp
) internal view returns (uint256) {
// get the rate between the pool token and the reserve token
Fraction memory poolRate = poolTokenRate(poolToken, reserveToken);
// get the rate between the reserves upon adding liquidity and now
Fraction memory addSpotRate = Fraction({ n: packedRates.addSpotRateN, d: packedRates.addSpotRateD });
Fraction memory removeSpotRate = Fraction({ n: packedRates.removeSpotRateN, d: packedRates.removeSpotRateD });
Fraction memory removeAverageRate =
Fraction({ n: packedRates.removeAverageRateN, d: packedRates.removeAverageRateD });
// calculate the protected amount of reserve tokens plus accumulated fee before compensation
uint256 total = protectedAmountPlusFee(poolAmount, poolRate, addSpotRate, removeSpotRate);
// calculate the impermanent loss
Fraction memory loss = impLoss(addSpotRate, removeAverageRate);
// calculate the protection level
Fraction memory level = protectionLevel(addTimestamp, removeTimestamp);
// calculate the compensation amount
return compensationAmount(reserveAmount, MathEx.max(reserveAmount, total), loss, level);
}
/**
* @dev transfers a position to a new provider
*
* @param id position id
* @param newProvider the new provider
*
* @return new position id
*/
function transferPosition(uint256 id, address newProvider)
external
override
protected
validAddress(newProvider)
returns (uint256)
{
return transferPosition(msg.sender, id, newProvider);
}
/**
* @dev transfers a position to a new provider and optionally notifies another contract
*
* @param id position id
* @param newProvider the new provider
* @param callback the callback contract to notify
* @param data custom data provided to the callback
*
* @return new position id
*/
function transferPositionAndNotify(
uint256 id,
address newProvider,
ITransferPositionCallback callback,
bytes calldata data
) external override protected validAddress(newProvider) validAddress(address(callback)) returns (uint256) {
uint256 newId = transferPosition(msg.sender, id, newProvider);
callback.onTransferPosition(newId, msg.sender, data);
return newId;
}
/**
* @dev transfers a position to a new provider
*
* @param provider the existing provider
* @param id position id
* @param newProvider the new provider
*
* @return new position id
*/
function transferPosition(
address provider,
uint256 id,
address newProvider
) internal returns (uint256) {
// remove the position from the store and update the stats and the last removal checkpoint
Position memory removedPos = removePosition(provider, id, PPM_RESOLUTION);
// add the position to the store, update the stats, and return the new id
return
addPosition(
newProvider,
removedPos.poolToken,
removedPos.reserveToken,
removedPos.poolAmount,
removedPos.reserveAmount,
removedPos.timestamp
);
}
/**
* @dev allows the caller to claim network token balance that is no longer locked
* note that the function can revert if the range is too large
*
* @param startIndex start index in the caller's list of locked balances
* @param endIndex end index in the caller's list of locked balances (exclusive)
*/
function claimBalance(uint256 startIndex, uint256 endIndex) external protected {
// get the locked balances from the store
(uint256[] memory amounts, uint256[] memory expirationTimes) =
_store.lockedBalanceRange(msg.sender, startIndex, endIndex);
uint256 totalAmount = 0;
uint256 length = amounts.length;
assert(length == expirationTimes.length);
// reverse iteration since we're removing from the list
for (uint256 i = length; i > 0; i--) {
uint256 index = i - 1;
if (expirationTimes[index] > time()) {
continue;
}
// remove the locked balance item
_store.removeLockedBalance(msg.sender, startIndex + index);
totalAmount = totalAmount.add(amounts[index]);
}
if (totalAmount > 0) {
// transfer the tokens to the caller in a single call
_wallet.withdrawTokens(IReserveToken(address(_networkToken)), msg.sender, totalAmount);
}
}
/**
* @dev returns the ROI for removing liquidity in the current state after providing liquidity with the given args
* the function assumes full protection is in effect
* return value is in PPM and can be larger than PPM_RESOLUTION for positive ROI, 1M = 0% ROI
*
* @param poolToken pool token
* @param reserveToken reserve token
* @param reserveAmount reserve token amount that was added
* @param poolRateN rate of 1 pool token in reserve token units when the liquidity was added (numerator)
* @param poolRateD rate of 1 pool token in reserve token units when the liquidity was added (denominator)
* @param reserveRateN rate of 1 reserve token in the other reserve token units when the liquidity was added (numerator)
* @param reserveRateD rate of 1 reserve token in the other reserve token units when the liquidity was added (denominator)
*
* @return ROI in PPM
*/
function poolROI(
IDSToken poolToken,
IReserveToken reserveToken,
uint256 reserveAmount,
uint256 poolRateN,
uint256 poolRateD,
uint256 reserveRateN,
uint256 reserveRateD
) external view returns (uint256) {
// calculate the amount of pool tokens based on the amount of reserve tokens
uint256 poolAmount = reserveAmount.mul(poolRateD).div(poolRateN);
// get the various rates between the reserves upon adding liquidity and now
PackedRates memory packedRates = packRates(poolToken, reserveToken, reserveRateN, reserveRateD);
// get the current return
uint256 protectedReturn =
removeLiquidityTargetAmount(
poolToken,
reserveToken,
poolAmount,
reserveAmount,
packedRates,
time().sub(_settings.maxProtectionDelay()),
time()
);
// calculate the ROI as the ratio between the current fully protected return and the initial amount
return protectedReturn.mul(PPM_RESOLUTION).div(reserveAmount);
}
/**
* @dev adds the position to the store and updates the stats
*
* @param provider the provider
* @param poolToken pool token
* @param reserveToken reserve token
* @param poolAmount amount of pool tokens to protect
* @param reserveAmount amount of reserve tokens to protect
* @param timestamp the timestamp of the position
*
* @return new position id
*/
function addPosition(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
uint256 poolAmount,
uint256 reserveAmount,
uint256 timestamp
) internal returns (uint256) {
// verify rate deviation as early as possible in order to reduce gas-cost for failing transactions
(Fraction memory spotRate, Fraction memory averageRate) = reserveTokenRates(poolToken, reserveToken);
verifyRateDeviation(spotRate.n, spotRate.d, averageRate.n, averageRate.d);
notifyEventSubscribersOnAddingLiquidity(provider, poolToken, reserveToken, poolAmount, reserveAmount);
_stats.increaseTotalAmounts(provider, poolToken, reserveToken, poolAmount, reserveAmount);
_stats.addProviderPool(provider, poolToken);
return
_store.addProtectedLiquidity(
provider,
poolToken,
reserveToken,
poolAmount,
reserveAmount,
spotRate.n,
spotRate.d,
timestamp
);
}
/**
* @dev removes the position from the store and updates the stats and the last removal checkpoint
*
* @param provider the provider
* @param id position id
* @param portion portion of the position to remove, in PPM
*
* @return a Position struct representing the removed liquidity
*/
function removePosition(
address provider,
uint256 id,
uint32 portion
) private returns (Position memory) {
Position memory pos = providerPosition(id, provider);
// verify that the pool is whitelisted
_poolWhitelisted(pos.poolToken);
// verify that the position is not removed on the same block in which it was added
require(pos.timestamp < time(), "ERR_TOO_EARLY");
if (portion == PPM_RESOLUTION) {
notifyEventSubscribersOnRemovingLiquidity(
id,
pos.provider,
pos.poolToken,
pos.reserveToken,
pos.poolAmount,
pos.reserveAmount
);
// remove the position from the provider
_store.removeProtectedLiquidity(id);
} else {
// remove a portion of the position from the provider
uint256 fullPoolAmount = pos.poolAmount;
uint256 fullReserveAmount = pos.reserveAmount;
pos.poolAmount = pos.poolAmount.mul(portion) / PPM_RESOLUTION;
pos.reserveAmount = pos.reserveAmount.mul(portion) / PPM_RESOLUTION;
notifyEventSubscribersOnRemovingLiquidity(
id,
pos.provider,
pos.poolToken,
pos.reserveToken,
pos.poolAmount,
pos.reserveAmount
);
_store.updateProtectedLiquidityAmounts(
id,
fullPoolAmount - pos.poolAmount,
fullReserveAmount - pos.reserveAmount
);
}
// update the statistics
_stats.decreaseTotalAmounts(pos.provider, pos.poolToken, pos.reserveToken, pos.poolAmount, pos.reserveAmount);
// update last liquidity removal checkpoint
_lastRemoveCheckpointStore.addCheckpoint(provider);
return pos;
}
/**
* @dev locks network tokens for the provider and emits the tokens locked event
*
* @param provider tokens provider
* @param amount amount of network tokens
*/
function lockTokens(address provider, uint256 amount) internal {
uint256 expirationTime = time().add(_settings.lockDuration());
_store.addLockedBalance(provider, amount, expirationTime);
}
/**
* @dev returns the rate of 1 pool token in reserve token units
*
* @param poolToken pool token
* @param reserveToken reserve token
*/
function poolTokenRate(IDSToken poolToken, IReserveToken reserveToken)
internal
view
virtual
returns (Fraction memory)
{
// get the pool token supply
uint256 poolTokenSupply = poolToken.totalSupply();
// get the reserve balance
IConverter converter = IConverter(payable(ownedBy(poolToken)));
uint256 reserveBalance = converter.getConnectorBalance(reserveToken);
// for standard pools, 50% of the pool supply value equals the value of each reserve
return Fraction({ n: reserveBalance.mul(2), d: poolTokenSupply });
}
/**
* @dev returns the spot rate and average rate of 1 reserve token in the other reserve token units
*
* @param poolToken pool token
* @param reserveToken reserve token
*
* @return spot rate
* @return average rate
*/
function reserveTokenRates(IDSToken poolToken, IReserveToken reserveToken)
internal
view
returns (Fraction memory, Fraction memory)
{
ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(poolToken)));
IReserveToken otherReserve = converterOtherReserve(converter, reserveToken);
(uint256 spotRateN, uint256 spotRateD) = converterReserveBalances(converter, otherReserve, reserveToken);
(uint256 averageRateN, uint256 averageRateD) = converter.recentAverageRate(reserveToken);
return (Fraction({ n: spotRateN, d: spotRateD }), Fraction({ n: averageRateN, d: averageRateD }));
}
/**
* @dev returns the various rates between the reserves
*
* @param poolToken pool token
* @param reserveToken reserve token
* @param addSpotRateN add spot rate numerator
* @param addSpotRateD add spot rate denominator
*
* @return see `struct PackedRates`
*/
function packRates(
IDSToken poolToken,
IReserveToken reserveToken,
uint256 addSpotRateN,
uint256 addSpotRateD
) internal view returns (PackedRates memory) {
(Fraction memory removeSpotRate, Fraction memory removeAverageRate) =
reserveTokenRates(poolToken, reserveToken);
assert(
addSpotRateN <= MAX_UINT128 &&
addSpotRateD <= MAX_UINT128 &&
removeSpotRate.n <= MAX_UINT128 &&
removeSpotRate.d <= MAX_UINT128 &&
removeAverageRate.n <= MAX_UINT128 &&
removeAverageRate.d <= MAX_UINT128
);
return
PackedRates({
addSpotRateN: uint128(addSpotRateN),
addSpotRateD: uint128(addSpotRateD),
removeSpotRateN: uint128(removeSpotRate.n),
removeSpotRateD: uint128(removeSpotRate.d),
removeAverageRateN: uint128(removeAverageRate.n),
removeAverageRateD: uint128(removeAverageRate.d)
});
}
/**
* @dev verifies that the deviation of the average rate from the spot rate is within the permitted range
* for example, if the maximum permitted deviation is 5%, then verify `95/100 <= average/spot <= 100/95`
*
* @param spotRateN spot rate numerator
* @param spotRateD spot rate denominator
* @param averageRateN average rate numerator
* @param averageRateD average rate denominator
*/
function verifyRateDeviation(
uint256 spotRateN,
uint256 spotRateD,
uint256 averageRateN,
uint256 averageRateD
) internal view {
uint256 ppmDelta = PPM_RESOLUTION - _settings.averageRateMaxDeviation();
uint256 min = spotRateN.mul(averageRateD).mul(ppmDelta).mul(ppmDelta);
uint256 mid = spotRateD.mul(averageRateN).mul(ppmDelta).mul(PPM_RESOLUTION);
uint256 max = spotRateN.mul(averageRateD).mul(PPM_RESOLUTION).mul(PPM_RESOLUTION);
require(min <= mid && mid <= max, "ERR_INVALID_RATE");
}
/**
* @dev utility to add liquidity to a converter
*
* @param converter converter
* @param reserveToken1 reserve token 1
* @param reserveToken2 reserve token 2
* @param reserveAmount1 reserve amount 1
* @param reserveAmount2 reserve amount 2
* @param value ETH amount to add
*/
function addLiquidity(
ILiquidityPoolConverter converter,
IReserveToken reserveToken1,
IReserveToken reserveToken2,
uint256 reserveAmount1,
uint256 reserveAmount2,
uint256 value
) internal {
IReserveToken[] memory reserveTokens = new IReserveToken[](2);
uint256[] memory amounts = new uint256[](2);
reserveTokens[0] = reserveToken1;
reserveTokens[1] = reserveToken2;
amounts[0] = reserveAmount1;
amounts[1] = reserveAmount2;
converter.addLiquidity{ value: value }(reserveTokens, amounts, 1);
}
/**
* @dev utility to remove liquidity from a converter
*
* @param poolToken pool token of the converter
* @param poolAmount amount of pool tokens to remove
* @param reserveToken1 reserve token 1
* @param reserveToken2 reserve token 2
*/
function removeLiquidity(
IDSToken poolToken,
uint256 poolAmount,
IReserveToken reserveToken1,
IReserveToken reserveToken2
) internal {
ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(poolToken)));
IReserveToken[] memory reserveTokens = new IReserveToken[](2);
uint256[] memory minReturns = new uint256[](2);
reserveTokens[0] = reserveToken1;
reserveTokens[1] = reserveToken2;
minReturns[0] = 1;
minReturns[1] = 1;
converter.removeLiquidity(poolAmount, reserveTokens, minReturns);
}
/**
* @dev returns a position from the store
*
* @param id position id
*
* @return a position
*/
function position(uint256 id) internal view returns (Position memory) {
Position memory pos;
(
pos.provider,
pos.poolToken,
pos.reserveToken,
pos.poolAmount,
pos.reserveAmount,
pos.reserveRateN,
pos.reserveRateD,
pos.timestamp
) = _store.protectedLiquidity(id);
return pos;
}
/**
* @dev returns a position from the store
*
* @param id position id
* @param provider authorized provider
*
* @return a position
*/
function providerPosition(uint256 id, address provider) internal view returns (Position memory) {
Position memory pos = position(id);
require(pos.provider == provider, "ERR_ACCESS_DENIED");
return pos;
}
/**
* @dev returns the protected amount of reserve tokens plus accumulated fee before compensation
*
* @param poolAmount pool token amount when the liquidity was added
* @param poolRate rate of 1 pool token in the related reserve token units
* @param addRate rate of 1 reserve token in the other reserve token units when the liquidity was added
* @param removeRate rate of 1 reserve token in the other reserve token units when the liquidity is removed
*
* @return protected amount of reserve tokens plus accumulated fee = sqrt(removeRate / addRate) * poolRate * poolAmount
*/
function protectedAmountPlusFee(
uint256 poolAmount,
Fraction memory poolRate,
Fraction memory addRate,
Fraction memory removeRate
) internal pure returns (uint256) {
uint256 n = MathEx.ceilSqrt(addRate.d.mul(removeRate.n)).mul(poolRate.n);
uint256 d = MathEx.floorSqrt(addRate.n.mul(removeRate.d)).mul(poolRate.d);
uint256 x = n * poolAmount;
if (x / n == poolAmount) {
return x / d;
}
(uint256 hi, uint256 lo) = n > poolAmount ? (n, poolAmount) : (poolAmount, n);
(uint256 p, uint256 q) = MathEx.reducedRatio(hi, d, MAX_UINT256 / lo);
uint256 min = (hi / d).mul(lo);
if (q > 0) {
return MathEx.max(min, (p * lo) / q);
}
return min;
}
/**
* @dev returns the impermanent loss incurred due to the change in rates between the reserve tokens
*
* @param prevRate previous rate between the reserves
* @param newRate new rate between the reserves
*
* @return impermanent loss (as a ratio)
*/
function impLoss(Fraction memory prevRate, Fraction memory newRate) internal pure returns (Fraction memory) {
uint256 ratioN = newRate.n.mul(prevRate.d);
uint256 ratioD = newRate.d.mul(prevRate.n);
uint256 prod = ratioN * ratioD;
uint256 root =
prod / ratioN == ratioD ? MathEx.floorSqrt(prod) : MathEx.floorSqrt(ratioN) * MathEx.floorSqrt(ratioD);
uint256 sum = ratioN.add(ratioD);
// the arithmetic below is safe because `x + y >= sqrt(x * y) * 2`
if (sum % 2 == 0) {
sum /= 2;
return Fraction({ n: sum - root, d: sum });
}
return Fraction({ n: sum - root * 2, d: sum });
}
/**
* @dev returns the protection level based on the timestamp and protection delays
*
* @param addTimestamp time at which the liquidity was added
* @param removeTimestamp time at which the liquidity is removed
*
* @return protection level (as a ratio)
*/
function protectionLevel(uint256 addTimestamp, uint256 removeTimestamp) internal view returns (Fraction memory) {
uint256 timeElapsed = removeTimestamp.sub(addTimestamp);
uint256 minProtectionDelay = _settings.minProtectionDelay();
uint256 maxProtectionDelay = _settings.maxProtectionDelay();
if (timeElapsed < minProtectionDelay) {
return Fraction({ n: 0, d: 1 });
}
if (timeElapsed >= maxProtectionDelay) {
return Fraction({ n: 1, d: 1 });
}
return Fraction({ n: timeElapsed, d: maxProtectionDelay });
}
/**
* @dev returns the compensation amount based on the impermanent loss and the protection level
*
* @param amount protected amount in units of the reserve token
* @param total amount plus fee in units of the reserve token
* @param loss protection level (as a ratio between 0 and 1)
* @param level impermanent loss (as a ratio between 0 and 1)
*
* @return compensation amount
*/
function compensationAmount(
uint256 amount,
uint256 total,
Fraction memory loss,
Fraction memory level
) internal pure returns (uint256) {
uint256 levelN = level.n.mul(amount);
uint256 levelD = level.d;
uint256 maxVal = MathEx.max(MathEx.max(levelN, levelD), total);
(uint256 lossN, uint256 lossD) = MathEx.reducedRatio(loss.n, loss.d, MAX_UINT256 / maxVal);
return total.mul(lossD.sub(lossN)).div(lossD).add(lossN.mul(levelN).div(lossD.mul(levelD)));
}
function networkCompensation(
uint256 targetAmount,
uint256 baseAmount,
PackedRates memory packedRates
) internal view returns (uint256) {
if (targetAmount <= baseAmount) {
return 0;
}
// calculate the delta in network tokens
uint256 delta =
(targetAmount - baseAmount).mul(packedRates.removeAverageRateN).div(packedRates.removeAverageRateD);
// the delta might be very small due to precision loss
// in which case no compensation will take place (gas optimization)
if (delta >= _settings.minNetworkCompensation()) {
return delta;
}
return 0;
}
// utility to mint network tokens
function mintNetworkTokens(
address owner,
IConverterAnchor poolAnchor,
uint256 amount
) private {
_systemStore.incNetworkTokensMinted(poolAnchor, amount);
_networkTokenGovernance.mint(owner, amount);
}
// utility to burn network tokens
function burnNetworkTokens(IConverterAnchor poolAnchor, uint256 amount) private {
_systemStore.decNetworkTokensMinted(poolAnchor, amount);
_networkTokenGovernance.burn(amount);
}
/**
* @dev notify event subscribers on adding liquidity
*
* @param provider liquidity provider
* @param poolToken pool token
* @param reserveToken reserve token
* @param poolAmount amount of pool tokens to protect
* @param reserveAmount amount of reserve tokens to protect
*/
function notifyEventSubscribersOnAddingLiquidity(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
uint256 poolAmount,
uint256 reserveAmount
) private {
address[] memory subscribers = _settings.subscribers();
uint256 length = subscribers.length;
for (uint256 i = 0; i < length; i++) {
ILiquidityProvisionEventsSubscriber(subscribers[i]).onAddingLiquidity(
provider,
poolToken,
reserveToken,
poolAmount,
reserveAmount
);
}
}
/**
* @dev notify event subscribers on removing liquidity
*
* @param id position id
* @param provider liquidity provider
* @param poolToken pool token
* @param reserveToken reserve token
* @param poolAmount amount of pool tokens to protect
* @param reserveAmount amount of reserve tokens to protect
*/
function notifyEventSubscribersOnRemovingLiquidity(
uint256 id,
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
uint256 poolAmount,
uint256 reserveAmount
) private {
address[] memory subscribers = _settings.subscribers();
uint256 length = subscribers.length;
for (uint256 i = 0; i < length; i++) {
ILiquidityProvisionEventsSubscriber(subscribers[i]).onRemovingLiquidity(
id,
provider,
poolToken,
reserveToken,
poolAmount,
reserveAmount
);
}
}
// utility to get the reserve balances
function converterReserveBalances(
IConverter converter,
IReserveToken reserveToken1,
IReserveToken reserveToken2
) private view returns (uint256, uint256) {
return (converter.getConnectorBalance(reserveToken1), converter.getConnectorBalance(reserveToken2));
}
// utility to get the other reserve
function converterOtherReserve(IConverter converter, IReserveToken thisReserve)
private
view
returns (IReserveToken)
{
IReserveToken otherReserve = converter.connectorTokens(0);
return otherReserve != thisReserve ? otherReserve : converter.connectorTokens(1);
}
// utility to get the owner
function ownedBy(IOwned owned) private view returns (address) {
return owned.owner();
}
/**
* @dev returns whether the provided reserve token is the network token
*
* @return whether the provided reserve token is the network token
*/
function isNetworkToken(IReserveToken reserveToken) private view returns (bool) {
return address(reserveToken) == address(_networkToken);
}
}
| * @dev Transfer position event callback interface/ | interface ITransferPositionCallback {
function onTransferPosition(
uint256 newId,
address provider,
bytes calldata data
) external;
}
| 6,978,237 | [
1,
5912,
1754,
871,
1348,
1560,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5831,
467,
5912,
2555,
2428,
288,
203,
565,
445,
603,
5912,
2555,
12,
203,
3639,
2254,
5034,
27598,
16,
203,
3639,
1758,
2893,
16,
203,
3639,
1731,
745,
892,
501,
203,
565,
262,
3903,
31,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x5F276242f111A23dD6308526d6d4876bfE53Bc53/sources/contracts/SBT.sol | * @dev See {IERC4671-ownerOf}./ | function ownerOf(uint256 tokenId) external view override(IERC4671, IERC4973) returns (address) {
_requireMinted(tokenId);
return _tokens[tokenId].owner;
}
| 9,630,514 | [
1,
9704,
288,
45,
654,
39,
8749,
11212,
17,
8443,
951,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
3410,
951,
12,
11890,
5034,
1147,
548,
13,
3903,
1476,
3849,
12,
45,
654,
39,
8749,
11212,
16,
467,
654,
39,
7616,
9036,
13,
1135,
261,
2867,
13,
288,
203,
3639,
389,
6528,
49,
474,
329,
12,
2316,
548,
1769,
203,
203,
3639,
327,
389,
7860,
63,
2316,
548,
8009,
8443,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.7.6;
import "./interfaces/GPv2Authentication.sol";
import "./libraries/GPv2EIP1967.sol";
import "./mixins/Initializable.sol";
import "./mixins/StorageAccessible.sol";
/// @title Gnosis Protocol v2 Access Control Contract
/// @author Gnosis Developers
contract GPv2AllowListAuthentication is
GPv2Authentication,
Initializable,
StorageAccessible
{
/// @dev The address of the manager that has permissions to add and remove
/// solvers.
address public manager;
/// @dev The set of allowed solvers. Allowed solvers have a value of `true`
/// in this mapping.
mapping(address => bool) private solvers;
/// @dev Event emitted when the manager changes.
event ManagerChanged(address newManager, address oldManager);
/// @dev Event emitted when a solver gets added.
event SolverAdded(address solver);
/// @dev Event emitted when a solver gets removed.
event SolverRemoved(address solver);
/// @dev Initialize the manager to a value.
///
/// This method is a contract initializer that is called exactly once after
/// creation. An initializer is used instead of a constructor so that this
/// contract can be used behind a proxy.
///
/// This initializer is idempotent.
///
/// @param manager_ The manager to initialize the contract with.
function initializeManager(address manager_) external initializer {
manager = manager_;
emit ManagerChanged(manager_, address(0));
}
/// @dev Modifier that ensures a method can only be called by the contract
/// manager. Reverts if called by other addresses.
modifier onlyManager() {
require(manager == msg.sender, "GPv2: caller not manager");
_;
}
/// @dev Modifier that ensures method can be either called by the contract
/// manager or the proxy owner.
///
/// This modifier assumes that the proxy uses an EIP-1967 compliant storage
/// slot for the admin.
modifier onlyManagerOrOwner() {
require(
manager == msg.sender || GPv2EIP1967.getAdmin() == msg.sender,
"GPv2: not authorized"
);
_;
}
/// @dev Set the manager for this contract.
///
/// This method can be called by the current manager (if they want to to
/// reliquish the role and give it to another address) or the contract
/// owner (i.e. the proxy admin).
///
/// @param manager_ The new contract manager address.
function setManager(address manager_) external onlyManagerOrOwner {
address oldManager = manager;
manager = manager_;
emit ManagerChanged(manager_, oldManager);
}
/// @dev Add an address to the set of allowed solvers. This method can only
/// be called by the contract manager.
///
/// This function is idempotent.
///
/// @param solver The solver address to add.
function addSolver(address solver) external onlyManager {
solvers[solver] = true;
emit SolverAdded(solver);
}
/// @dev Removes an address to the set of allowed solvers. This method can
/// only be called by the contract manager.
///
/// This function is idempotent.
///
/// @param solver The solver address to remove.
function removeSolver(address solver) external onlyManager {
solvers[solver] = false;
emit SolverRemoved(solver);
}
/// @inheritdoc GPv2Authentication
function isSolver(address prospectiveSolver)
external
view
override
returns (bool)
{
return solvers[prospectiveSolver];
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.7.6;
/// @title Gnosis Protocol v2 Authentication Interface
/// @author Gnosis Developers
interface GPv2Authentication {
/// @dev determines whether the provided address is an authenticated solver.
/// @param prospectiveSolver the address of prospective solver.
/// @return true when prospectiveSolver is an authenticated solver, otherwise false.
function isSolver(address prospectiveSolver) external view returns (bool);
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.7.6;
library GPv2EIP1967 {
/// @dev The storage slot where the proxy administrator is stored, defined
/// as `keccak256('eip1967.proxy.admin') - 1`.
bytes32 internal constant ADMIN_SLOT =
hex"b53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103";
/// @dev Returns the address stored in the EIP-1967 administrator storage
/// slot for the current contract. If this method is not called from an
/// contract behind an EIP-1967 proxy, then it will most likely return
/// `address(0)`, as the implementation slot is likely to be unset.
///
/// @return admin The administrator address.
function getAdmin() internal view returns (address admin) {
// solhint-disable-next-line no-inline-assembly
assembly {
admin := sload(ADMIN_SLOT)
}
}
/// @dev Sets the storage at the EIP-1967 administrator slot to be the
/// specified address.
///
/// @param admin The administrator address to set.
function setAdmin(address admin) internal {
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(ADMIN_SLOT, admin)
}
}
}
// SPDX-License-Identifier: MIT
// Vendored from OpenZeppelin contracts with minor modifications:
// - Modified Solidity version
// - Formatted code
// - Shortned revert messages
// - Inlined `Address.isContract` implementation
// <https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/proxy/Initializable.sol>
pragma solidity ^0.7.6;
/**
* @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 {UpgradeableProxy-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 || _isConstructor() || !_initialized,
"Initializable: 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) {
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(address())
}
return size == 0;
}
}
// SPDX-License-Identifier: LGPL-3.0-only
// Vendored from Gnosis utility contracts with minor modifications:
// - Modified Solidity version
// - Formatted code
// - Added linter directives to ignore low level call and assembly warnings
// <https://github.com/gnosis/util-contracts/blob/v3.1.0-solc-7/contracts/StorageAccessible.sol>
pragma solidity ^0.7.6;
/// @title ViewStorageAccessible - Interface on top of StorageAccessible base class to allow simulations from view functions
interface ViewStorageAccessible {
/**
* @dev Same as `simulateDelegatecall` on StorageAccessible. Marked as view so that it can be called from external contracts
* that want to run simulations from within view functions. Will revert if the invoked simulation attempts to change state.
*/
function simulateDelegatecall(
address targetContract,
bytes memory calldataPayload
) external view returns (bytes memory);
/**
* @dev Same as `getStorageAt` on StorageAccessible. This method allows reading aribtrary ranges of storage.
*/
function getStorageAt(uint256 offset, uint256 length)
external
view
returns (bytes memory);
}
/// @title StorageAccessible - generic base contract that allows callers to access all internal storage.
contract StorageAccessible {
/**
* @dev Reads `length` bytes of storage in the currents contract
* @param offset - the offset in the current contract's storage in words to start reading from
* @param length - the number of words (32 bytes) of data to read
* @return the bytes that were read.
*/
function getStorageAt(uint256 offset, uint256 length)
external
view
returns (bytes memory)
{
bytes memory result = new bytes(length * 32);
for (uint256 index = 0; index < length; index++) {
// solhint-disable-next-line no-inline-assembly
assembly {
let word := sload(add(offset, index))
mstore(add(add(result, 0x20), mul(index, 0x20)), word)
}
}
return result;
}
/**
* @dev Performs a delegetecall on a targetContract in the context of self.
* Internally reverts execution to avoid side effects (making it static). Catches revert and returns encoded result as bytes.
* @param targetContract Address of the contract containing the code to execute.
* @param calldataPayload Calldata that should be sent to the target contract (encoded method name and arguments).
*/
function simulateDelegatecall(
address targetContract,
bytes memory calldataPayload
) public returns (bytes memory response) {
bytes memory innerCall =
abi.encodeWithSelector(
this.simulateDelegatecallInternal.selector,
targetContract,
calldataPayload
);
// solhint-disable-next-line avoid-low-level-calls
(, response) = address(this).call(innerCall);
bool innerSuccess = response[response.length - 1] == 0x01;
setLength(response, response.length - 1);
if (innerSuccess) {
return response;
} else {
revertWith(response);
}
}
/**
* @dev Performs a delegetecall on a targetContract in the context of self.
* Internally reverts execution to avoid side effects (making it static). Returns encoded result as revert message
* concatenated with the success flag of the inner call as a last byte.
* @param targetContract Address of the contract containing the code to execute.
* @param calldataPayload Calldata that should be sent to the target contract (encoded method name and arguments).
*/
function simulateDelegatecallInternal(
address targetContract,
bytes memory calldataPayload
) external returns (bytes memory response) {
bool success;
// solhint-disable-next-line avoid-low-level-calls
(success, response) = targetContract.delegatecall(calldataPayload);
revertWith(abi.encodePacked(response, success));
}
function revertWith(bytes memory response) internal pure {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(response, 0x20), mload(response))
}
}
function setLength(bytes memory buffer, uint256 length) internal pure {
// solhint-disable-next-line no-inline-assembly
assembly {
mstore(buffer, length)
}
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.7.6;
import "../GPv2AllowListAuthentication.sol";
contract GPv2AllowListAuthenticationV2 is GPv2AllowListAuthentication {
function newMethod() external pure returns (uint256) {
return 1337;
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.7.6;
import "../GPv2AllowListAuthentication.sol";
import "../libraries/GPv2EIP1967.sol";
contract GPv2AllowListAuthenticationTestInterface is
GPv2AllowListAuthentication
{
constructor(address owner) {
GPv2EIP1967.setAdmin(owner);
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./GPv2VaultRelayer.sol";
import "./interfaces/GPv2Authentication.sol";
import "./interfaces/IERC20.sol";
import "./interfaces/IVault.sol";
import "./libraries/GPv2Interaction.sol";
import "./libraries/GPv2Order.sol";
import "./libraries/GPv2Trade.sol";
import "./libraries/GPv2Transfer.sol";
import "./libraries/SafeCast.sol";
import "./libraries/SafeMath.sol";
import "./mixins/GPv2Signing.sol";
import "./mixins/ReentrancyGuard.sol";
import "./mixins/StorageAccessible.sol";
/// @title Gnosis Protocol v2 Settlement Contract
/// @author Gnosis Developers
contract GPv2Settlement is GPv2Signing, ReentrancyGuard, StorageAccessible {
using GPv2Order for bytes;
using GPv2Transfer for IVault;
using SafeCast for int256;
using SafeCast for uint256;
using SafeMath for uint256;
/// @dev The authenticator is used to determine who can call the settle function.
/// That is, only authorised solvers have the ability to invoke settlements.
/// Any valid authenticator implements an isSolver method called by the onlySolver
/// modifier below.
GPv2Authentication public immutable authenticator;
/// @dev The Balancer Vault the protocol uses for managing user funds.
IVault public immutable vault;
/// @dev The Balancer Vault relayer which can interact on behalf of users.
/// This contract is created during deployment
GPv2VaultRelayer public immutable vaultRelayer;
/// @dev Map each user order by UID to the amount that has been filled so
/// far. If this amount is larger than or equal to the amount traded in the
/// order (amount sold for sell orders, amount bought for buy orders) then
/// the order cannot be traded anymore. If the order is fill or kill, then
/// this value is only used to determine whether the order has already been
/// executed.
mapping(bytes => uint256) public filledAmount;
/// @dev Event emitted for each executed trade.
event Trade(
address indexed owner,
IERC20 sellToken,
IERC20 buyToken,
uint256 sellAmount,
uint256 buyAmount,
uint256 feeAmount,
bytes orderUid
);
/// @dev Event emitted for each executed interaction.
///
/// For gas effeciency, only the interaction calldata selector (first 4
/// bytes) is included in the event. For interactions without calldata or
/// whose calldata is shorter than 4 bytes, the selector will be `0`.
event Interaction(address indexed target, uint256 value, bytes4 selector);
/// @dev Event emitted when a settlement complets
event Settlement(address indexed solver);
/// @dev Event emitted when an order is invalidated.
event OrderInvalidated(address indexed owner, bytes orderUid);
constructor(GPv2Authentication authenticator_, IVault vault_) {
authenticator = authenticator_;
vault = vault_;
vaultRelayer = new GPv2VaultRelayer(vault_);
}
// solhint-disable-next-line no-empty-blocks
receive() external payable {
// NOTE: Include an empty receive function so that the settlement
// contract can receive Ether from contract interactions.
}
/// @dev This modifier is called by settle function to block any non-listed
/// senders from settling batches.
modifier onlySolver {
require(authenticator.isSolver(msg.sender), "GPv2: not a solver");
_;
}
/// @dev Modifier to ensure that an external function is only callable as a
/// settlement interaction.
modifier onlyInteraction {
require(address(this) == msg.sender, "GPv2: not an interaction");
_;
}
/// @dev Settle the specified orders at a clearing price. Note that it is
/// the responsibility of the caller to ensure that all GPv2 invariants are
/// upheld for the input settlement, otherwise this call will revert.
/// Namely:
/// - All orders are valid and signed
/// - Accounts have sufficient balance and approval.
/// - Settlement contract has sufficient balance to execute trades. Note
/// this implies that the accumulated fees held in the contract can also
/// be used for settlement. This is OK since:
/// - Solvers need to be authorized
/// - Misbehaving solvers will be slashed for abusing accumulated fees for
/// settlement
/// - Critically, user orders are entirely protected
///
/// @param tokens An array of ERC20 tokens to be traded in the settlement.
/// Trades encode tokens as indices into this array.
/// @param clearingPrices An array of clearing prices where the `i`-th price
/// is for the `i`-th token in the [`tokens`] array.
/// @param trades Trades for signed orders.
/// @param interactions Smart contract interactions split into three
/// separate lists to be run before the settlement, during the settlement
/// and after the settlement respectively.
function settle(
IERC20[] calldata tokens,
uint256[] calldata clearingPrices,
GPv2Trade.Data[] calldata trades,
GPv2Interaction.Data[][3] calldata interactions
) external nonReentrant onlySolver {
executeInteractions(interactions[0]);
(
GPv2Transfer.Data[] memory inTransfers,
GPv2Transfer.Data[] memory outTransfers
) = computeTradeExecutions(tokens, clearingPrices, trades);
vaultRelayer.transferFromAccounts(inTransfers);
executeInteractions(interactions[1]);
vault.transferToAccounts(outTransfers);
executeInteractions(interactions[2]);
emit Settlement(msg.sender);
}
/// @dev Settle an order directly against Balancer V2 pools.
///
/// @param swaps The Balancer V2 swap steps to use for trading.
/// @param tokens An array of ERC20 tokens to be traded in the settlement.
/// Swaps and the trade encode tokens as indices into this array.
/// @param trade The trade to match directly against Balancer liquidity. The
/// order will always be fully executed, so the trade's `executedAmount`
/// field is used to represent a swap limit amount.
function swap(
IVault.BatchSwapStep[] calldata swaps,
IERC20[] calldata tokens,
GPv2Trade.Data calldata trade
) external nonReentrant onlySolver {
RecoveredOrder memory recoveredOrder = allocateRecoveredOrder();
GPv2Order.Data memory order = recoveredOrder.data;
recoverOrderFromTrade(recoveredOrder, tokens, trade);
IVault.SwapKind kind =
order.kind == GPv2Order.KIND_SELL
? IVault.SwapKind.GIVEN_IN
: IVault.SwapKind.GIVEN_OUT;
IVault.FundManagement memory funds;
funds.sender = recoveredOrder.owner;
funds.fromInternalBalance =
order.sellTokenBalance == GPv2Order.BALANCE_INTERNAL;
funds.recipient = payable(recoveredOrder.receiver);
funds.toInternalBalance =
order.buyTokenBalance == GPv2Order.BALANCE_INTERNAL;
int256[] memory limits = new int256[](tokens.length);
uint256 limitAmount = trade.executedAmount;
// NOTE: Array allocation initializes elements to 0, so we only need to
// set the limits we care about. This ensures that the swap will respect
// the order's limit price.
if (order.kind == GPv2Order.KIND_SELL) {
require(limitAmount >= order.buyAmount, "GPv2: limit too low");
limits[trade.sellTokenIndex] = order.sellAmount.toInt256();
limits[trade.buyTokenIndex] = -limitAmount.toInt256();
} else {
require(limitAmount <= order.sellAmount, "GPv2: limit too high");
limits[trade.sellTokenIndex] = limitAmount.toInt256();
limits[trade.buyTokenIndex] = -order.buyAmount.toInt256();
}
GPv2Transfer.Data memory feeTransfer;
feeTransfer.account = recoveredOrder.owner;
feeTransfer.token = order.sellToken;
feeTransfer.amount = order.feeAmount;
feeTransfer.balance = order.sellTokenBalance;
int256[] memory tokenDeltas =
vaultRelayer.batchSwapWithFee(
kind,
swaps,
tokens,
funds,
limits,
// NOTE: Specify a deadline to ensure that an expire order
// cannot be used to trade.
order.validTo,
feeTransfer
);
bytes memory orderUid = recoveredOrder.uid;
uint256 executedSellAmount =
tokenDeltas[trade.sellTokenIndex].toUint256();
uint256 executedBuyAmount =
(-tokenDeltas[trade.buyTokenIndex]).toUint256();
// NOTE: Check that the orders were completely filled and update their
// filled amounts to avoid replaying them. The limit price and order
// validity have already been verified when executing the swap through
// the `limit` and `deadline` parameters.
require(filledAmount[orderUid] == 0, "GPv2: order filled");
if (order.kind == GPv2Order.KIND_SELL) {
require(
executedSellAmount == order.sellAmount,
"GPv2: sell amount not respected"
);
filledAmount[orderUid] = order.sellAmount;
} else {
require(
executedBuyAmount == order.buyAmount,
"GPv2: buy amount not respected"
);
filledAmount[orderUid] = order.buyAmount;
}
emit Trade(
recoveredOrder.owner,
order.sellToken,
order.buyToken,
executedSellAmount,
executedBuyAmount,
order.feeAmount,
orderUid
);
emit Settlement(msg.sender);
}
/// @dev Invalidate onchain an order that has been signed offline.
///
/// @param orderUid The unique identifier of the order that is to be made
/// invalid after calling this function. The user that created the order
/// must be the the sender of this message. See [`extractOrderUidParams`]
/// for details on orderUid.
function invalidateOrder(bytes calldata orderUid) external {
(, address owner, ) = orderUid.extractOrderUidParams();
require(owner == msg.sender, "GPv2: caller does not own order");
filledAmount[orderUid] = uint256(-1);
emit OrderInvalidated(owner, orderUid);
}
/// @dev Free storage from the filled amounts of **expired** orders to claim
/// a gas refund. This method can only be called as an interaction.
///
/// @param orderUids The unique identifiers of the expired order to free
/// storage for.
function freeFilledAmountStorage(bytes[] calldata orderUids)
external
onlyInteraction
{
freeOrderStorage(filledAmount, orderUids);
}
/// @dev Free storage from the pre signatures of **expired** orders to claim
/// a gas refund. This method can only be called as an interaction.
///
/// @param orderUids The unique identifiers of the expired order to free
/// storage for.
function freePreSignatureStorage(bytes[] calldata orderUids)
external
onlyInteraction
{
freeOrderStorage(preSignature, orderUids);
}
/// @dev Process all trades one at a time returning the computed net in and
/// out transfers for the trades.
///
/// This method reverts if processing of any single trade fails. See
/// [`computeTradeExecution`] for more details.
///
/// @param tokens An array of ERC20 tokens to be traded in the settlement.
/// @param clearingPrices An array of token clearing prices.
/// @param trades Trades for signed orders.
/// @return inTransfers Array of in transfers of executed sell amounts.
/// @return outTransfers Array of out transfers of executed buy amounts.
function computeTradeExecutions(
IERC20[] calldata tokens,
uint256[] calldata clearingPrices,
GPv2Trade.Data[] calldata trades
)
internal
returns (
GPv2Transfer.Data[] memory inTransfers,
GPv2Transfer.Data[] memory outTransfers
)
{
RecoveredOrder memory recoveredOrder = allocateRecoveredOrder();
inTransfers = new GPv2Transfer.Data[](trades.length);
outTransfers = new GPv2Transfer.Data[](trades.length);
for (uint256 i = 0; i < trades.length; i++) {
GPv2Trade.Data calldata trade = trades[i];
recoverOrderFromTrade(recoveredOrder, tokens, trade);
computeTradeExecution(
recoveredOrder,
clearingPrices[trade.sellTokenIndex],
clearingPrices[trade.buyTokenIndex],
trade.executedAmount,
inTransfers[i],
outTransfers[i]
);
}
}
/// @dev Compute the in and out transfer amounts for a single trade.
/// This function reverts if:
/// - The order has expired
/// - The order's limit price is not respected
/// - The order gets over-filled
/// - The fee discount is larger than the executed fee
///
/// @param recoveredOrder The recovered order to process.
/// @param sellPrice The price of the order's sell token.
/// @param buyPrice The price of the order's buy token.
/// @param executedAmount The portion of the order to execute. This will be
/// ignored for fill-or-kill orders.
/// @param inTransfer Memory location for computed executed sell amount
/// transfer.
/// @param outTransfer Memory location for computed executed buy amount
/// transfer.
function computeTradeExecution(
RecoveredOrder memory recoveredOrder,
uint256 sellPrice,
uint256 buyPrice,
uint256 executedAmount,
GPv2Transfer.Data memory inTransfer,
GPv2Transfer.Data memory outTransfer
) internal {
GPv2Order.Data memory order = recoveredOrder.data;
bytes memory orderUid = recoveredOrder.uid;
// solhint-disable-next-line not-rely-on-time
require(order.validTo >= block.timestamp, "GPv2: order expired");
// NOTE: The following computation is derived from the equation:
// ```
// amount_x * price_x = amount_y * price_y
// ```
// Intuitively, if a chocolate bar is 0,50€ and a beer is 4€, 1 beer
// is roughly worth 8 chocolate bars (`1 * 4 = 8 * 0.5`). From this
// equation, we can derive:
// - The limit price for selling `x` and buying `y` is respected iff
// ```
// limit_x * price_x >= limit_y * price_y
// ```
// - The executed amount of token `y` given some amount of `x` and
// clearing prices is:
// ```
// amount_y = amount_x * price_x / price_y
// ```
require(
order.sellAmount.mul(sellPrice) >= order.buyAmount.mul(buyPrice),
"GPv2: limit price not respected"
);
uint256 executedSellAmount;
uint256 executedBuyAmount;
uint256 executedFeeAmount;
uint256 currentFilledAmount;
if (order.kind == GPv2Order.KIND_SELL) {
if (order.partiallyFillable) {
executedSellAmount = executedAmount;
executedFeeAmount = order.feeAmount.mul(executedSellAmount).div(
order.sellAmount
);
} else {
executedSellAmount = order.sellAmount;
executedFeeAmount = order.feeAmount;
}
executedBuyAmount = executedSellAmount.mul(sellPrice).ceilDiv(
buyPrice
);
currentFilledAmount = filledAmount[orderUid].add(
executedSellAmount
);
require(
currentFilledAmount <= order.sellAmount,
"GPv2: order filled"
);
} else {
if (order.partiallyFillable) {
executedBuyAmount = executedAmount;
executedFeeAmount = order.feeAmount.mul(executedBuyAmount).div(
order.buyAmount
);
} else {
executedBuyAmount = order.buyAmount;
executedFeeAmount = order.feeAmount;
}
executedSellAmount = executedBuyAmount.mul(buyPrice).div(sellPrice);
currentFilledAmount = filledAmount[orderUid].add(executedBuyAmount);
require(
currentFilledAmount <= order.buyAmount,
"GPv2: order filled"
);
}
executedSellAmount = executedSellAmount.add(executedFeeAmount);
filledAmount[orderUid] = currentFilledAmount;
emit Trade(
recoveredOrder.owner,
order.sellToken,
order.buyToken,
executedSellAmount,
executedBuyAmount,
executedFeeAmount,
orderUid
);
inTransfer.account = recoveredOrder.owner;
inTransfer.token = order.sellToken;
inTransfer.amount = executedSellAmount;
inTransfer.balance = order.sellTokenBalance;
outTransfer.account = recoveredOrder.receiver;
outTransfer.token = order.buyToken;
outTransfer.amount = executedBuyAmount;
outTransfer.balance = order.buyTokenBalance;
}
/// @dev Execute a list of arbitrary contract calls from this contract.
/// @param interactions The list of interactions to execute.
function executeInteractions(GPv2Interaction.Data[] calldata interactions)
internal
{
for (uint256 i; i < interactions.length; i++) {
GPv2Interaction.Data calldata interaction = interactions[i];
// To prevent possible attack on user funds, we explicitly disable
// any interactions with the vault relayer contract.
require(
interaction.target != address(vaultRelayer),
"GPv2: forbidden interaction"
);
GPv2Interaction.execute(interaction);
emit Interaction(
interaction.target,
interaction.value,
GPv2Interaction.selector(interaction)
);
}
}
/// @dev Claims refund for the specified storage and order UIDs.
///
/// This method reverts if any of the orders are still valid.
///
/// @param orderUids Order refund data for freeing storage.
/// @param orderStorage Order storage mapped on a UID.
function freeOrderStorage(
mapping(bytes => uint256) storage orderStorage,
bytes[] calldata orderUids
) internal {
for (uint256 i = 0; i < orderUids.length; i++) {
bytes calldata orderUid = orderUids[i];
(, , uint32 validTo) = orderUid.extractOrderUidParams();
// solhint-disable-next-line not-rely-on-time
require(validTo < block.timestamp, "GPv2: order still valid");
orderStorage[orderUid] = 0;
}
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./interfaces/IERC20.sol";
import "./interfaces/IVault.sol";
import "./libraries/GPv2Transfer.sol";
/// @title Gnosis Protocol v2 Vault Relayer Contract
/// @author Gnosis Developers
contract GPv2VaultRelayer {
using GPv2Transfer for IVault;
/// @dev The creator of the contract which has special permissions. This
/// value is set at creation time and cannot change.
address private immutable creator;
/// @dev The vault this relayer is for.
IVault private immutable vault;
constructor(IVault vault_) {
creator = msg.sender;
vault = vault_;
}
/// @dev Modifier that ensures that a function can only be called by the
/// creator of this contract.
modifier onlyCreator {
require(msg.sender == creator, "GPv2: not creator");
_;
}
/// @dev Transfers all sell amounts for the executed trades from their
/// owners to the caller.
///
/// This function reverts if:
/// - The caller is not the creator of the vault relayer
/// - Any ERC20 transfer fails
///
/// @param transfers The transfers to execute.
function transferFromAccounts(GPv2Transfer.Data[] calldata transfers)
external
onlyCreator
{
vault.transferFromAccounts(transfers, msg.sender);
}
/// @dev Performs a Balancer batched swap on behalf of a user and sends a
/// fee to the caller.
///
/// This function reverts if:
/// - The caller is not the creator of the vault relayer
/// - The swap fails
/// - The fee transfer fails
///
/// @param kind The Balancer swap kind, this can either be `GIVEN_IN` for
/// sell orders or `GIVEN_OUT` for buy orders.
/// @param swaps The swaps to perform.
/// @param tokens The tokens for the swaps. Swaps encode to and from tokens
/// as indices into this array.
/// @param funds The fund management settings, specifying the user the swap
/// is being performed for as well as the recipient of the proceeds.
/// @param limits Swap limits for encoding limit prices.
/// @param deadline The deadline for the swap.
/// @param feeTransfer The transfer data for the caller fee.
/// @return tokenDeltas The executed swap amounts.
function batchSwapWithFee(
IVault.SwapKind kind,
IVault.BatchSwapStep[] calldata swaps,
IERC20[] memory tokens,
IVault.FundManagement memory funds,
int256[] memory limits,
uint256 deadline,
GPv2Transfer.Data calldata feeTransfer
) external onlyCreator returns (int256[] memory tokenDeltas) {
tokenDeltas = vault.batchSwap(
kind,
swaps,
tokens,
funds,
limits,
deadline
);
vault.fastTransferFromAccount(feeTransfer, msg.sender);
}
}
// SPDX-License-Identifier: MIT
// Vendored from OpenZeppelin contracts with minor modifications:
// - Modified Solidity version
// - Formatted code
// - Added `name`, `symbol` and `decimals` function declarations
// <https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/token/ERC20/IERC20.sol>
pragma solidity ^0.7.6;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the number of decimals the token uses.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender)
external
view
returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./IERC20.sol";
/**
* @dev Minimal interface for the Vault core contract only containing methods
* used by Gnosis Protocol V2. Original source:
* <https://github.com/balancer-labs/balancer-core-v2/blob/v1.0.0/contracts/vault/interfaces/IVault.sol>
*/
interface IVault {
// Internal Balance
//
// Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later
// transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination
// when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced
// gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users.
//
// Internal Balance management features batching, which means a single contract call can be used to perform multiple
// operations of different kinds, with different senders and recipients, at once.
/**
* @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer)
* and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as
* it lets integrators reuse a user's Vault allowance.
*
* For each operation, if the caller is not `sender`, it must be an authorized relayer for them.
*/
function manageUserBalance(UserBalanceOp[] memory ops) external payable;
/**
* @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received
without manual WETH wrapping or unwrapping.
*/
struct UserBalanceOp {
UserBalanceOpKind kind;
IERC20 asset;
uint256 amount;
address sender;
address payable recipient;
}
// There are four possible operations in `manageUserBalance`:
//
// - DEPOSIT_INTERNAL
// Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding
// `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`.
//
// ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped
// and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is
// relevant for relayers).
//
// Emits an `InternalBalanceChanged` event.
//
//
// - WITHDRAW_INTERNAL
// Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`.
//
// ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send
// it to the recipient as ETH.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_INTERNAL
// Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_EXTERNAL
// Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by
// relayers, as it lets them reuse a user's Vault allowance.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `ExternalBalanceTransfer` event.
enum UserBalanceOpKind {
DEPOSIT_INTERNAL,
WITHDRAW_INTERNAL,
TRANSFER_INTERNAL,
TRANSFER_EXTERNAL
}
// Swaps
//
// Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this,
// they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be
// aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote.
//
// The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence.
// In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'),
// and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out').
// More complex swaps, such as one token in to multiple tokens out can be achieved by batching together
// individual swaps.
//
// There are two swap kinds:
// - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the
// `onSwap` hook) the amount of tokens out (to send to the recipient).
// - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines
// (via the `onSwap` hook) the amount of tokens in (to receive from the sender).
//
// Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with
// the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated
// tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended
// swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at
// the final intended token.
//
// In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal
// Balance) after all individual swaps have been completed, and the net token balance change computed. This makes
// certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost
// much less gas than they would otherwise.
//
// It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple
// Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only
// updating the Pool's internal accounting).
//
// To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token
// involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the
// minimum amount of tokens to receive (by passing a negative value) is specified.
//
// Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after
// this point in time (e.g. if the transaction failed to be included in a block promptly).
//
// If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do
// the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be
// passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the
// same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers).
//
// Finally, Internal Balance can be used when either sending or receiving tokens.
enum SwapKind {GIVEN_IN, GIVEN_OUT}
/**
* @dev Performs a swap with a single Pool.
*
* If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens
* taken from the Pool, which must be greater than or equal to `limit`.
*
* If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens
* sent to the Pool, which must be less than or equal to `limit`.
*
* Internal Balance usage and the recipient are determined by the `funds` struct.
*
* Emits a `Swap` event.
*/
function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
) external payable returns (uint256);
/**
* @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on
* the `kind` value.
*
* `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address).
* Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct SingleSwap {
bytes32 poolId;
SwapKind kind;
IERC20 assetIn;
IERC20 assetOut;
uint256 amount;
bytes userData;
}
/**
* @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either
* the amount of tokens sent to or received from the Pool, depending on the `kind` value.
*
* Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the
* Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at
* the same index in the `assets` array.
*
* Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a
* Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or
* `amountOut` depending on the swap kind.
*
* Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out
* of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal
* the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`.
*
* The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses,
* or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and
* out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to
* or unwrapped from WETH by the Vault.
*
* Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies
* the minimum or maximum amount of each token the vault is allowed to transfer.
*
* `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the
* equivalent `swap` call.
*
* Emits `Swap` events.
*/
function batchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IERC20[] memory assets,
FundManagement memory funds,
int256[] memory limits,
uint256 deadline
) external payable returns (int256[] memory);
/**
* @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the
* `assets` array passed to that function, and ETH assets are converted to WETH.
*
* If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out
* from the previous swap, depending on the swap kind.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct BatchSwapStep {
bytes32 poolId;
uint256 assetInIndex;
uint256 assetOutIndex;
uint256 amount;
bytes userData;
}
/**
* @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the
* `recipient` account.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20
* transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender`
* must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of
* `joinPool`.
*
* If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of
* transferred. This matches the behavior of `exitPool`.
*
* Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a
* revert.
*/
struct FundManagement {
address sender;
bool fromInternalBalance;
address payable recipient;
bool toInternalBalance;
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.7.6;
/// @title Gnosis Protocol v2 Interaction Library
/// @author Gnosis Developers
library GPv2Interaction {
/// @dev Interaction data for performing arbitrary contract interactions.
/// Submitted to [`GPv2Settlement.settle`] for code execution.
struct Data {
address target;
uint256 value;
bytes callData;
}
/// @dev Execute an arbitrary contract interaction.
///
/// @param interaction Interaction data.
function execute(Data calldata interaction) internal {
address target = interaction.target;
uint256 value = interaction.value;
bytes calldata callData = interaction.callData;
// NOTE: Use assembly to call the interaction instead of a low level
// call for two reasons:
// - We don't want to copy the return data, since we discard it for
// interactions.
// - Solidity will under certain conditions generate code to copy input
// calldata twice to memory (the second being a "memcopy loop").
// <https://github.com/gnosis/gp-v2-contracts/pull/417#issuecomment-775091258>
// solhint-disable-next-line no-inline-assembly
assembly {
let freeMemoryPointer := mload(0x40)
calldatacopy(freeMemoryPointer, callData.offset, callData.length)
if iszero(
call(
gas(),
target,
value,
freeMemoryPointer,
callData.length,
0,
0
)
) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
}
/// @dev Extracts the Solidity ABI selector for the specified interaction.
///
/// @param interaction Interaction data.
/// @return result The 4 byte function selector of the call encoded in
/// this interaction.
function selector(Data calldata interaction)
internal
pure
returns (bytes4 result)
{
bytes calldata callData = interaction.callData;
if (callData.length >= 4) {
// NOTE: Read the first word of the interaction's calldata. The
// value does not need to be shifted since `bytesN` values are left
// aligned, and the value does not need to be masked since masking
// occurs when the value is accessed and not stored:
// <https://docs.soliditylang.org/en/v0.7.6/abi-spec.html#encoding-of-indexed-event-parameters>
// <https://docs.soliditylang.org/en/v0.7.6/assembly.html#access-to-external-variables-functions-and-libraries>
// solhint-disable-next-line no-inline-assembly
assembly {
result := calldataload(callData.offset)
}
}
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.7.6;
import "../interfaces/IERC20.sol";
/// @title Gnosis Protocol v2 Order Library
/// @author Gnosis Developers
library GPv2Order {
/// @dev The complete data for a Gnosis Protocol order. This struct contains
/// all order parameters that are signed for submitting to GP.
struct Data {
IERC20 sellToken;
IERC20 buyToken;
address receiver;
uint256 sellAmount;
uint256 buyAmount;
uint32 validTo;
bytes32 appData;
uint256 feeAmount;
bytes32 kind;
bool partiallyFillable;
bytes32 sellTokenBalance;
bytes32 buyTokenBalance;
}
/// @dev The order EIP-712 type hash for the [`GPv2Order.Data`] struct.
///
/// This value is pre-computed from the following expression:
/// ```
/// keccak256(
/// "Order(" +
/// "address sellToken," +
/// "address buyToken," +
/// "address receiver," +
/// "uint256 sellAmount," +
/// "uint256 buyAmount," +
/// "uint32 validTo," +
/// "bytes32 appData," +
/// "uint256 feeAmount," +
/// "string kind," +
/// "bool partiallyFillable" +
/// "string sellTokenBalance" +
/// "string buyTokenBalance" +
/// ")"
/// )
/// ```
bytes32 internal constant TYPE_HASH =
hex"d5a25ba2e97094ad7d83dc28a6572da797d6b3e7fc6663bd93efb789fc17e489";
/// @dev The marker value for a sell order for computing the order struct
/// hash. This allows the EIP-712 compatible wallets to display a
/// descriptive string for the order kind (instead of 0 or 1).
///
/// This value is pre-computed from the following expression:
/// ```
/// keccak256("sell")
/// ```
bytes32 internal constant KIND_SELL =
hex"f3b277728b3fee749481eb3e0b3b48980dbbab78658fc419025cb16eee346775";
/// @dev The OrderKind marker value for a buy order for computing the order
/// struct hash.
///
/// This value is pre-computed from the following expression:
/// ```
/// keccak256("buy")
/// ```
bytes32 internal constant KIND_BUY =
hex"6ed88e868af0a1983e3886d5f3e95a2fafbd6c3450bc229e27342283dc429ccc";
/// @dev The TokenBalance marker value for using direct ERC20 balances for
/// computing the order struct hash.
///
/// This value is pre-computed from the following expression:
/// ```
/// keccak256("erc20")
/// ```
bytes32 internal constant BALANCE_ERC20 =
hex"5a28e9363bb942b639270062aa6bb295f434bcdfc42c97267bf003f272060dc9";
/// @dev The TokenBalance marker value for using Balancer Vault external
/// balances (in order to re-use Vault ERC20 approvals) for computing the
/// order struct hash.
///
/// This value is pre-computed from the following expression:
/// ```
/// keccak256("external")
/// ```
bytes32 internal constant BALANCE_EXTERNAL =
hex"abee3b73373acd583a130924aad6dc38cfdc44ba0555ba94ce2ff63980ea0632";
/// @dev The TokenBalance marker value for using Balancer Vault internal
/// balances for computing the order struct hash.
///
/// This value is pre-computed from the following expression:
/// ```
/// keccak256("internal")
/// ```
bytes32 internal constant BALANCE_INTERNAL =
hex"4ac99ace14ee0a5ef932dc609df0943ab7ac16b7583634612f8dc35a4289a6ce";
/// @dev Marker address used to indicate that the receiver of the trade
/// proceeds should the owner of the order.
///
/// This is chosen to be `address(0)` for gas efficiency as it is expected
/// to be the most common case.
address internal constant RECEIVER_SAME_AS_OWNER = address(0);
/// @dev The byte length of an order unique identifier.
uint256 internal constant UID_LENGTH = 56;
/// @dev Returns the actual receiver for an order. This function checks
/// whether or not the [`receiver`] field uses the marker value to indicate
/// it is the same as the order owner.
///
/// @return receiver The actual receiver of trade proceeds.
function actualReceiver(Data memory order, address owner)
internal
pure
returns (address receiver)
{
if (order.receiver == RECEIVER_SAME_AS_OWNER) {
receiver = owner;
} else {
receiver = order.receiver;
}
}
/// @dev Return the EIP-712 signing hash for the specified order.
///
/// @param order The order to compute the EIP-712 signing hash for.
/// @param domainSeparator The EIP-712 domain separator to use.
/// @return orderDigest The 32 byte EIP-712 struct hash.
function hash(Data memory order, bytes32 domainSeparator)
internal
pure
returns (bytes32 orderDigest)
{
bytes32 structHash;
// NOTE: Compute the EIP-712 order struct hash in place. As suggested
// in the EIP proposal, noting that the order struct has 10 fields, and
// including the type hash `(12 + 1) * 32 = 416` bytes to hash.
// <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#rationale-for-encodedata>
// solhint-disable-next-line no-inline-assembly
assembly {
let dataStart := sub(order, 32)
let temp := mload(dataStart)
mstore(dataStart, TYPE_HASH)
structHash := keccak256(dataStart, 416)
mstore(dataStart, temp)
}
// NOTE: Now that we have the struct hash, compute the EIP-712 signing
// hash using scratch memory past the free memory pointer. The signing
// hash is computed from `"\x19\x01" || domainSeparator || structHash`.
// <https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html#layout-in-memory>
// <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#specification>
// solhint-disable-next-line no-inline-assembly
assembly {
let freeMemoryPointer := mload(0x40)
mstore(freeMemoryPointer, "\x19\x01")
mstore(add(freeMemoryPointer, 2), domainSeparator)
mstore(add(freeMemoryPointer, 34), structHash)
orderDigest := keccak256(freeMemoryPointer, 66)
}
}
/// @dev Packs order UID parameters into the specified memory location. The
/// result is equivalent to `abi.encodePacked(...)` with the difference that
/// it allows re-using the memory for packing the order UID.
///
/// This function reverts if the order UID buffer is not the correct size.
///
/// @param orderUid The buffer pack the order UID parameters into.
/// @param orderDigest The EIP-712 struct digest derived from the order
/// parameters.
/// @param owner The address of the user who owns this order.
/// @param validTo The epoch time at which the order will stop being valid.
function packOrderUidParams(
bytes memory orderUid,
bytes32 orderDigest,
address owner,
uint32 validTo
) internal pure {
require(orderUid.length == UID_LENGTH, "GPv2: uid buffer overflow");
// NOTE: Write the order UID to the allocated memory buffer. The order
// parameters are written to memory in **reverse order** as memory
// operations write 32-bytes at a time and we want to use a packed
// encoding. This means, for example, that after writing the value of
// `owner` to bytes `20:52`, writing the `orderDigest` to bytes `0:32`
// will **overwrite** bytes `20:32`. This is desirable as addresses are
// only 20 bytes and `20:32` should be `0`s:
//
// | 1111111111222222222233333333334444444444555555
// byte | 01234567890123456789012345678901234567890123456789012345
// -------+---------------------------------------------------------
// field | [.........orderDigest..........][......owner.......][vT]
// -------+---------------------------------------------------------
// mstore | [000000000000000000000000000.vT]
// | [00000000000.......owner.......]
// | [.........orderDigest..........]
//
// Additionally, since Solidity `bytes memory` are length prefixed,
// 32 needs to be added to all the offsets.
//
// solhint-disable-next-line no-inline-assembly
assembly {
mstore(add(orderUid, 56), validTo)
mstore(add(orderUid, 52), owner)
mstore(add(orderUid, 32), orderDigest)
}
}
/// @dev Extracts specific order information from the standardized unique
/// order id of the protocol.
///
/// @param orderUid The unique identifier used to represent an order in
/// the protocol. This uid is the packed concatenation of the order digest,
/// the validTo order parameter and the address of the user who created the
/// order. It is used by the user to interface with the contract directly,
/// and not by calls that are triggered by the solvers.
/// @return orderDigest The EIP-712 signing digest derived from the order
/// parameters.
/// @return owner The address of the user who owns this order.
/// @return validTo The epoch time at which the order will stop being valid.
function extractOrderUidParams(bytes calldata orderUid)
internal
pure
returns (
bytes32 orderDigest,
address owner,
uint32 validTo
)
{
require(orderUid.length == UID_LENGTH, "GPv2: invalid uid");
// Use assembly to efficiently decode packed calldata.
// solhint-disable-next-line no-inline-assembly
assembly {
orderDigest := calldataload(orderUid.offset)
owner := shr(96, calldataload(add(orderUid.offset, 32)))
validTo := shr(224, calldataload(add(orderUid.offset, 52)))
}
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.7.6;
import "../interfaces/IERC20.sol";
import "../mixins/GPv2Signing.sol";
import "./GPv2Order.sol";
/// @title Gnosis Protocol v2 Trade Library.
/// @author Gnosis Developers
library GPv2Trade {
using GPv2Order for GPv2Order.Data;
using GPv2Order for bytes;
/// @dev A struct representing a trade to be executed as part a batch
/// settlement.
struct Data {
uint256 sellTokenIndex;
uint256 buyTokenIndex;
address receiver;
uint256 sellAmount;
uint256 buyAmount;
uint32 validTo;
bytes32 appData;
uint256 feeAmount;
uint256 flags;
uint256 executedAmount;
bytes signature;
}
/// @dev Extracts the order data and signing scheme for the specified trade.
///
/// @param trade The trade.
/// @param tokens The list of tokens included in the settlement. The token
/// indices in the trade parameters map to tokens in this array.
/// @param order The memory location to extract the order data to.
function extractOrder(
Data calldata trade,
IERC20[] calldata tokens,
GPv2Order.Data memory order
) internal pure returns (GPv2Signing.Scheme signingScheme) {
order.sellToken = tokens[trade.sellTokenIndex];
order.buyToken = tokens[trade.buyTokenIndex];
order.receiver = trade.receiver;
order.sellAmount = trade.sellAmount;
order.buyAmount = trade.buyAmount;
order.validTo = trade.validTo;
order.appData = trade.appData;
order.feeAmount = trade.feeAmount;
(
order.kind,
order.partiallyFillable,
order.sellTokenBalance,
order.buyTokenBalance,
signingScheme
) = extractFlags(trade.flags);
}
/// @dev Decodes trade flags.
///
/// Trade flags are used to tightly encode information on how to decode
/// an order. Examples that directly affect the structure of an order are
/// the kind of order (either a sell or a buy order) as well as whether the
/// order is partially fillable or if it is a "fill-or-kill" order. It also
/// encodes the signature scheme used to validate the order. As the most
/// likely values are fill-or-kill sell orders by an externally owned
/// account, the flags are chosen such that `0x00` represents this kind of
/// order. The flags byte uses the following format:
///
/// ```
/// bit | 31 ... | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
/// ----+----------+---+---+-------+---+---+
/// | reserved | * * | * | * * | * | * |
/// | | | | | | |
/// | | | | | | +---- order kind bit, 0 for a sell order
/// | | | | | | and 1 for a buy order
/// | | | | | |
/// | | | | | +-------- order fill bit, 0 for fill-or-kill
/// | | | | | and 1 for a partially fillable order
/// | | | | |
/// | | | +---+------------ use internal sell token balance bit:
/// | | | 0x: ERC20 token balance
/// | | | 10: external Balancer Vault balance
/// | | | 11: internal Balancer Vault balance
/// | | |
/// | | +-------------------- use buy token balance bit
/// | | 0: ERC20 token balance
/// | | 1: internal Balancer Vault balance
/// | |
/// +---+------------------------ signature scheme bits:
/// 00: EIP-712
/// 01: eth_sign
/// 10: EIP-1271
/// 11: pre_sign
/// ```
function extractFlags(uint256 flags)
internal
pure
returns (
bytes32 kind,
bool partiallyFillable,
bytes32 sellTokenBalance,
bytes32 buyTokenBalance,
GPv2Signing.Scheme signingScheme
)
{
if (flags & 0x01 == 0) {
kind = GPv2Order.KIND_SELL;
} else {
kind = GPv2Order.KIND_BUY;
}
partiallyFillable = flags & 0x02 != 0;
if (flags & 0x08 == 0) {
sellTokenBalance = GPv2Order.BALANCE_ERC20;
} else if (flags & 0x04 == 0) {
sellTokenBalance = GPv2Order.BALANCE_EXTERNAL;
} else {
sellTokenBalance = GPv2Order.BALANCE_INTERNAL;
}
if (flags & 0x10 == 0) {
buyTokenBalance = GPv2Order.BALANCE_ERC20;
} else {
buyTokenBalance = GPv2Order.BALANCE_INTERNAL;
}
// NOTE: Take advantage of the fact that Solidity will revert if the
// following expression does not produce a valid enum value. This means
// we check here that the leading reserved bits must be 0.
signingScheme = GPv2Signing.Scheme(flags >> 5);
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.7.6;
pragma abicoder v2;
import "../interfaces/IERC20.sol";
import "../interfaces/IVault.sol";
import "./GPv2Order.sol";
import "./GPv2SafeERC20.sol";
/// @title Gnosis Protocol v2 Transfers
/// @author Gnosis Developers
library GPv2Transfer {
using GPv2SafeERC20 for IERC20;
/// @dev Transfer data.
struct Data {
address account;
IERC20 token;
uint256 amount;
bytes32 balance;
}
/// @dev Ether marker address used to indicate an Ether transfer.
address internal constant BUY_ETH_ADDRESS =
0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @dev Execute the specified transfer from the specified account to a
/// recipient. The recipient will either receive internal Vault balances or
/// ERC20 token balances depending on whether the account is using internal
/// balances or not.
///
/// This method is used for transferring fees to the settlement contract
/// when settling a single order directly with Balancer.
///
/// Note that this method is subtly different from `transferFromAccounts`
/// with a single transfer with respect to how it deals with internal
/// balances. Specifically, this method will perform an **internal balance
/// transfer to the settlement contract instead of a withdrawal to the
/// external balance of the settlement contract** for trades that specify
/// trading with internal balances. This is done as a gas optimization in
/// the single order "fast-path".
///
/// @param vault The Balancer vault to use.
/// @param transfer The transfer to perform specifying the sender account.
/// @param recipient The recipient for the transfer.
function fastTransferFromAccount(
IVault vault,
Data calldata transfer,
address recipient
) internal {
require(
address(transfer.token) != BUY_ETH_ADDRESS,
"GPv2: cannot transfer native ETH"
);
if (transfer.balance == GPv2Order.BALANCE_ERC20) {
transfer.token.safeTransferFrom(
transfer.account,
recipient,
transfer.amount
);
} else {
IVault.UserBalanceOp[] memory balanceOps =
new IVault.UserBalanceOp[](1);
IVault.UserBalanceOp memory balanceOp = balanceOps[0];
balanceOp.kind = transfer.balance == GPv2Order.BALANCE_EXTERNAL
? IVault.UserBalanceOpKind.TRANSFER_EXTERNAL
: IVault.UserBalanceOpKind.TRANSFER_INTERNAL;
balanceOp.asset = transfer.token;
balanceOp.amount = transfer.amount;
balanceOp.sender = transfer.account;
balanceOp.recipient = payable(recipient);
vault.manageUserBalance(balanceOps);
}
}
/// @dev Execute the specified transfers from the specified accounts to a
/// single recipient. The recipient will receive all transfers as ERC20
/// token balances, regardless of whether or not the accounts are using
/// internal Vault balances.
///
/// This method is used for accumulating user balances into the settlement
/// contract.
///
/// @param vault The Balancer vault to use.
/// @param transfers The batched transfers to perform specifying the
/// sender accounts.
/// @param recipient The single recipient for all the transfers.
function transferFromAccounts(
IVault vault,
Data[] calldata transfers,
address recipient
) internal {
// NOTE: Allocate buffer of Vault balance operations large enough to
// hold all GP transfers. This is done to avoid re-allocations (which
// are gas inefficient) while still allowing all transfers to be batched
// into a single Vault call.
IVault.UserBalanceOp[] memory balanceOps =
new IVault.UserBalanceOp[](transfers.length);
uint256 balanceOpCount = 0;
for (uint256 i = 0; i < transfers.length; i++) {
Data calldata transfer = transfers[i];
require(
address(transfer.token) != BUY_ETH_ADDRESS,
"GPv2: cannot transfer native ETH"
);
if (transfer.balance == GPv2Order.BALANCE_ERC20) {
transfer.token.safeTransferFrom(
transfer.account,
recipient,
transfer.amount
);
} else {
IVault.UserBalanceOp memory balanceOp =
balanceOps[balanceOpCount++];
balanceOp.kind = transfer.balance == GPv2Order.BALANCE_EXTERNAL
? IVault.UserBalanceOpKind.TRANSFER_EXTERNAL
: IVault.UserBalanceOpKind.WITHDRAW_INTERNAL;
balanceOp.asset = transfer.token;
balanceOp.amount = transfer.amount;
balanceOp.sender = transfer.account;
balanceOp.recipient = payable(recipient);
}
}
if (balanceOpCount > 0) {
truncateBalanceOpsArray(balanceOps, balanceOpCount);
vault.manageUserBalance(balanceOps);
}
}
/// @dev Execute the specified transfers to their respective accounts.
///
/// This method is used for paying out trade proceeds from the settlement
/// contract.
///
/// @param vault The Balancer vault to use.
/// @param transfers The batched transfers to perform.
function transferToAccounts(IVault vault, Data[] memory transfers)
internal
{
IVault.UserBalanceOp[] memory balanceOps =
new IVault.UserBalanceOp[](transfers.length);
uint256 balanceOpCount = 0;
for (uint256 i = 0; i < transfers.length; i++) {
Data memory transfer = transfers[i];
if (address(transfer.token) == BUY_ETH_ADDRESS) {
require(
transfer.balance != GPv2Order.BALANCE_INTERNAL,
"GPv2: unsupported internal ETH"
);
payable(transfer.account).transfer(transfer.amount);
} else if (transfer.balance == GPv2Order.BALANCE_ERC20) {
transfer.token.safeTransfer(transfer.account, transfer.amount);
} else {
IVault.UserBalanceOp memory balanceOp =
balanceOps[balanceOpCount++];
balanceOp.kind = IVault.UserBalanceOpKind.DEPOSIT_INTERNAL;
balanceOp.asset = transfer.token;
balanceOp.amount = transfer.amount;
balanceOp.sender = address(this);
balanceOp.recipient = payable(transfer.account);
}
}
if (balanceOpCount > 0) {
truncateBalanceOpsArray(balanceOps, balanceOpCount);
vault.manageUserBalance(balanceOps);
}
}
/// @dev Truncate a Vault balance operation array to its actual size.
///
/// This method **does not** check whether or not the new length is valid,
/// and specifying a size that is larger than the array's actual length is
/// undefined behaviour.
///
/// @param balanceOps The memory array of balance operations to truncate.
/// @param newLength The new length to set.
function truncateBalanceOpsArray(
IVault.UserBalanceOp[] memory balanceOps,
uint256 newLength
) private pure {
// NOTE: Truncate the vault transfers array to the specified length.
// This is done by setting the array's length which occupies the first
// word in memory pointed to by the `balanceOps` memory variable.
// <https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html>
// solhint-disable-next-line no-inline-assembly
assembly {
mstore(balanceOps, newLength)
}
}
}
// SPDX-License-Identifier: MIT
// Vendored from OpenZeppelin contracts with minor modifications:
// - Modified Solidity version
// - Formatted code
// - Shortened revert messages
// - Removed unused methods
// - Convert to `type(*).*` notation
// <https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/utils/SafeCast.sol>
pragma solidity ^0.7.6;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such 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.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: not positive");
return uint256(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(
value <= uint256(type(int256).max),
"SafeCast: int256 overflow"
);
return int256(value);
}
}
// SPDX-License-Identifier: MIT
// Vendored from OpenZeppelin contracts with minor modifications:
// - Modified Solidity version
// - Formatted code
// - Shortened some revert messages
// - Removed unused methods
// - Added `ceilDiv` method
// <https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/math/SafeMath.sol>
pragma solidity ^0.7.6;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
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: mul 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 0");
return a / b;
}
/**
* @dev Returns the ceiling integer division of two unsigned integers,
* reverting on division by zero. The result is rounded towards up the
* nearest integer, instead of truncating the fractional part.
*
* Requirements:
*
* - The divisor cannot be zero.
* - The sum of the dividend and divisor cannot overflow.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: ceiling division by 0");
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.7.6;
import "../interfaces/GPv2EIP1271.sol";
import "../libraries/GPv2Order.sol";
import "../libraries/GPv2Trade.sol";
/// @title Gnosis Protocol v2 Signing Library.
/// @author Gnosis Developers
abstract contract GPv2Signing {
using GPv2Order for GPv2Order.Data;
using GPv2Order for bytes;
/// @dev Recovered trade data containing the extracted order and the
/// recovered owner address.
struct RecoveredOrder {
GPv2Order.Data data;
bytes uid;
address owner;
address receiver;
}
/// @dev Signing scheme used for recovery.
enum Scheme {Eip712, EthSign, Eip1271, PreSign}
/// @dev The EIP-712 domain type hash used for computing the domain
/// separator.
bytes32 private constant DOMAIN_TYPE_HASH =
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
/// @dev The EIP-712 domain name used for computing the domain separator.
bytes32 private constant DOMAIN_NAME = keccak256("Gnosis Protocol");
/// @dev The EIP-712 domain version used for computing the domain separator.
bytes32 private constant DOMAIN_VERSION = keccak256("v2");
/// @dev Marker value indicating an order is pre-signed.
uint256 private constant PRE_SIGNED =
uint256(keccak256("GPv2Signing.Scheme.PreSign"));
/// @dev The domain separator used for signing orders that gets mixed in
/// making signatures for different domains incompatible. This domain
/// separator is computed following the EIP-712 standard and has replay
/// protection mixed in so that signed orders are only valid for specific
/// GPv2 contracts.
bytes32 public immutable domainSeparator;
/// @dev Storage indicating whether or not an order has been signed by a
/// particular address.
mapping(bytes => uint256) public preSignature;
/// @dev Event that is emitted when an account either pre-signs an order or
/// revokes an existing pre-signature.
event PreSignature(address indexed owner, bytes orderUid, bool signed);
constructor() {
// NOTE: Currently, the only way to get the chain ID in solidity is
// using assembly.
uint256 chainId;
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPE_HASH,
DOMAIN_NAME,
DOMAIN_VERSION,
chainId,
address(this)
)
);
}
/// @dev Sets a presignature for the specified order UID.
///
/// @param orderUid The unique identifier of the order to pre-sign.
function setPreSignature(bytes calldata orderUid, bool signed) external {
(, address owner, ) = orderUid.extractOrderUidParams();
require(owner == msg.sender, "GPv2: cannot presign order");
if (signed) {
preSignature[orderUid] = PRE_SIGNED;
} else {
preSignature[orderUid] = 0;
}
emit PreSignature(owner, orderUid, signed);
}
/// @dev Returns an empty recovered order with a pre-allocated buffer for
/// packing the unique identifier.
///
/// @return recoveredOrder The empty recovered order data.
function allocateRecoveredOrder()
internal
pure
returns (RecoveredOrder memory recoveredOrder)
{
recoveredOrder.uid = new bytes(GPv2Order.UID_LENGTH);
}
/// @dev Extracts order data and recovers the signer from the specified
/// trade.
///
/// @param recoveredOrder Memory location used for writing the recovered order data.
/// @param tokens The list of tokens included in the settlement. The token
/// indices in the trade parameters map to tokens in this array.
/// @param trade The trade data to recover the order data from.
function recoverOrderFromTrade(
RecoveredOrder memory recoveredOrder,
IERC20[] calldata tokens,
GPv2Trade.Data calldata trade
) internal view {
GPv2Order.Data memory order = recoveredOrder.data;
Scheme signingScheme = GPv2Trade.extractOrder(trade, tokens, order);
(bytes32 orderDigest, address owner) =
recoverOrderSigner(order, signingScheme, trade.signature);
recoveredOrder.uid.packOrderUidParams(
orderDigest,
owner,
order.validTo
);
recoveredOrder.owner = owner;
recoveredOrder.receiver = order.actualReceiver(owner);
}
/// @dev The length of any signature from an externally owned account.
uint256 private constant ECDSA_SIGNATURE_LENGTH = 65;
/// @dev Recovers an order's signer from the specified order and signature.
///
/// @param order The order to recover a signature for.
/// @param signingScheme The signing scheme.
/// @param signature The signature bytes.
/// @return orderDigest The computed order hash.
/// @return owner The recovered address from the specified signature.
function recoverOrderSigner(
GPv2Order.Data memory order,
Scheme signingScheme,
bytes calldata signature
) internal view returns (bytes32 orderDigest, address owner) {
orderDigest = order.hash(domainSeparator);
if (signingScheme == Scheme.Eip712) {
owner = recoverEip712Signer(orderDigest, signature);
} else if (signingScheme == Scheme.EthSign) {
owner = recoverEthsignSigner(orderDigest, signature);
} else if (signingScheme == Scheme.Eip1271) {
owner = recoverEip1271Signer(orderDigest, signature);
} else {
// signingScheme == Scheme.PreSign
owner = recoverPreSigner(orderDigest, signature, order.validTo);
}
}
/// @dev Perform an ECDSA recover for the specified message and calldata
/// signature.
///
/// The signature is encoded by tighyly packing the following struct:
/// ```
/// struct EncodedSignature {
/// bytes32 r;
/// bytes32 s;
/// uint8 v;
/// }
/// ```
///
/// @param message The signed message.
/// @param encodedSignature The encoded signature.
function ecdsaRecover(bytes32 message, bytes calldata encodedSignature)
internal
pure
returns (address signer)
{
require(
encodedSignature.length == ECDSA_SIGNATURE_LENGTH,
"GPv2: malformed ecdsa signature"
);
bytes32 r;
bytes32 s;
uint8 v;
// NOTE: Use assembly to efficiently decode signature data.
// solhint-disable-next-line no-inline-assembly
assembly {
// r = uint256(encodedSignature[0:32])
r := calldataload(encodedSignature.offset)
// s = uint256(encodedSignature[32:64])
s := calldataload(add(encodedSignature.offset, 32))
// v = uint8(encodedSignature[64])
v := shr(248, calldataload(add(encodedSignature.offset, 64)))
}
signer = ecrecover(message, v, r, s);
require(signer != address(0), "GPv2: invalid ecdsa signature");
}
/// @dev Decodes signature bytes originating from an EIP-712-encoded
/// signature.
///
/// EIP-712 signs typed data. The specifications are described in the
/// related EIP (<https://eips.ethereum.org/EIPS/eip-712>).
///
/// EIP-712 signatures are encoded as standard ECDSA signatures as described
/// in the corresponding decoding function [`ecdsaRecover`].
///
/// @param orderDigest The EIP-712 signing digest derived from the order
/// parameters.
/// @param encodedSignature Calldata pointing to tightly packed signature
/// bytes.
/// @return owner The address of the signer.
function recoverEip712Signer(
bytes32 orderDigest,
bytes calldata encodedSignature
) internal pure returns (address owner) {
owner = ecdsaRecover(orderDigest, encodedSignature);
}
/// @dev Decodes signature bytes originating from the output of the eth_sign
/// RPC call.
///
/// The specifications are described in the Ethereum documentation
/// (<https://eth.wiki/json-rpc/API#eth_sign>).
///
/// eth_sign signatures are encoded as standard ECDSA signatures as
/// described in the corresponding decoding function
/// [`ecdsaRecover`].
///
/// @param orderDigest The EIP-712 signing digest derived from the order
/// parameters.
/// @param encodedSignature Calldata pointing to tightly packed signature
/// bytes.
/// @return owner The address of the signer.
function recoverEthsignSigner(
bytes32 orderDigest,
bytes calldata encodedSignature
) internal pure returns (address owner) {
// The signed message is encoded as:
// `"\x19Ethereum Signed Message:\n" || length || data`, where
// the length is a constant (32 bytes) and the data is defined as:
// `orderDigest`.
bytes32 ethsignDigest =
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
orderDigest
)
);
owner = ecdsaRecover(ethsignDigest, encodedSignature);
}
/// @dev Verifies the input calldata as an EIP-1271 contract signature and
/// returns the address of the signer.
///
/// The encoded signature tightly packs the following struct:
///
/// ```
/// struct EncodedEip1271Signature {
/// address owner;
/// bytes signature;
/// }
/// ```
///
/// This function enforces that the encoded data stores enough bytes to
/// cover the full length of the decoded signature.
///
/// @param encodedSignature The encoded EIP-1271 signature.
/// @param orderDigest The EIP-712 signing digest derived from the order
/// parameters.
/// @return owner The address of the signer.
function recoverEip1271Signer(
bytes32 orderDigest,
bytes calldata encodedSignature
) internal view returns (address owner) {
// NOTE: Use assembly to read the verifier address from the encoded
// signature bytes.
// solhint-disable-next-line no-inline-assembly
assembly {
// owner = address(encodedSignature[0:20])
owner := shr(96, calldataload(encodedSignature.offset))
}
// NOTE: Configure prettier to ignore the following line as it causes
// a panic in the Solidity plugin.
// prettier-ignore
bytes calldata signature = encodedSignature[20:];
require(
EIP1271Verifier(owner).isValidSignature(orderDigest, signature) ==
GPv2EIP1271.MAGICVALUE,
"GPv2: invalid eip1271 signature"
);
}
/// @dev Verifies the order has been pre-signed. The signature is the
/// address of the signer of the order.
///
/// @param orderDigest The EIP-712 signing digest derived from the order
/// parameters.
/// @param encodedSignature The pre-sign signature reprenting the order UID.
/// @param validTo The order expiry timestamp.
/// @return owner The address of the signer.
function recoverPreSigner(
bytes32 orderDigest,
bytes calldata encodedSignature,
uint32 validTo
) internal view returns (address owner) {
require(encodedSignature.length == 20, "GPv2: malformed presignature");
// NOTE: Use assembly to read the owner address from the encoded
// signature bytes.
// solhint-disable-next-line no-inline-assembly
assembly {
// owner = address(encodedSignature[0:20])
owner := shr(96, calldataload(encodedSignature.offset))
}
bytes memory orderUid = new bytes(GPv2Order.UID_LENGTH);
orderUid.packOrderUidParams(orderDigest, owner, validTo);
require(
preSignature[orderUid] == PRE_SIGNED,
"GPv2: order not presigned"
);
}
}
// SPDX-License-Identifier: MIT
// Vendored from OpenZeppelin contracts with minor modifications:
// - Modified Solidity version
// - Formatted code
// <https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/utils/ReentrancyGuard.sol>
pragma solidity ^0.7.6;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.7.6;
import "../interfaces/IERC20.sol";
/// @title Gnosis Protocol v2 Safe ERC20 Transfer Library
/// @author Gnosis Developers
/// @dev Gas-efficient version of Openzeppelin's SafeERC20 contract that notably
/// does not revert when calling a non-contract.
library GPv2SafeERC20 {
/// @dev Wrapper around a call to the ERC20 function `transfer` that reverts
/// also when the token returns `false`.
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
bytes4 selector_ = token.transfer.selector;
// solhint-disable-next-line no-inline-assembly
assembly {
let freeMemoryPointer := mload(0x40)
mstore(freeMemoryPointer, selector_)
mstore(
add(freeMemoryPointer, 4),
and(to, 0xffffffffffffffffffffffffffffffffffffffff)
)
mstore(add(freeMemoryPointer, 36), value)
if iszero(call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
require(getLastTansferResult(token), "GPv2: failed transfer");
}
/// @dev Wrapper around a call to the ERC20 function `transferFrom` that
/// reverts also when the token returns `false`.
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
bytes4 selector_ = token.transferFrom.selector;
// solhint-disable-next-line no-inline-assembly
assembly {
let freeMemoryPointer := mload(0x40)
mstore(freeMemoryPointer, selector_)
mstore(
add(freeMemoryPointer, 4),
and(from, 0xffffffffffffffffffffffffffffffffffffffff)
)
mstore(
add(freeMemoryPointer, 36),
and(to, 0xffffffffffffffffffffffffffffffffffffffff)
)
mstore(add(freeMemoryPointer, 68), value)
if iszero(call(gas(), token, 0, freeMemoryPointer, 100, 0, 0)) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
require(getLastTansferResult(token), "GPv2: failed transferFrom");
}
/// @dev Verifies that the last return was a successful `transfer*` call.
/// This is done by checking that the return data is either empty, or
/// is a valid ABI encoded boolean.
function getLastTansferResult(IERC20 token)
private
view
returns (bool success)
{
// NOTE: Inspecting previous return data requires assembly. Note that
// we write the return data to memory 0 in the case where the return
// data size is 32, this is OK since the first 64 bytes of memory are
// reserved by Solidy as a scratch space that can be used within
// assembly blocks.
// <https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html>
// solhint-disable-next-line no-inline-assembly
assembly {
/// @dev Revert with an ABI encoded Solidity error with a message
/// that fits into 32-bytes.
///
/// An ABI encoded Solidity error has the following memory layout:
///
/// ------------+----------------------------------
/// byte range | value
/// ------------+----------------------------------
/// 0x00..0x04 | selector("Error(string)")
/// 0x04..0x24 | string offset (always 0x20)
/// 0x24..0x44 | string length
/// 0x44..0x64 | string value, padded to 32-bytes
function revertWithMessage(length, message) {
mstore(0x00, "\x08\xc3\x79\xa0")
mstore(0x04, 0x20)
mstore(0x24, length)
mstore(0x44, message)
revert(0x00, 0x64)
}
switch returndatasize()
// Non-standard ERC20 transfer without return.
case 0 {
// NOTE: When the return data size is 0, verify that there
// is code at the address. This is done in order to maintain
// compatibility with Solidity calling conventions.
// <https://docs.soliditylang.org/en/v0.7.6/control-structures.html#external-function-calls>
if iszero(extcodesize(token)) {
revertWithMessage(20, "GPv2: not a contract")
}
success := 1
}
// Standard ERC20 transfer returning boolean success value.
case 32 {
returndatacopy(0, 0, returndatasize())
// NOTE: For ABI encoding v1, any non-zero value is accepted
// as `true` for a boolean. In order to stay compatible with
// OpenZeppelin's `SafeERC20` library which is known to work
// with the existing ERC20 implementation we care about,
// make sure we return success for any non-zero return value
// from the `transfer*` call.
success := iszero(iszero(mload(0)))
}
default {
revertWithMessage(31, "GPv2: malformed transfer result")
}
}
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.7.6;
library GPv2EIP1271 {
/// @dev Value returned by a call to `isValidSignature` if the signature
/// was verified successfully. The value is defined in EIP-1271 as:
/// bytes4(keccak256("isValidSignature(bytes32,bytes)"))
bytes4 internal constant MAGICVALUE = 0x1626ba7e;
}
/// @title EIP1271 Interface
/// @dev Standardized interface for an implementation of smart contract
/// signatures as described in EIP-1271. The code that follows is identical to
/// the code in the standard with the exception of formatting and syntax
/// changes to adapt the code to our Solidity version.
interface EIP1271Verifier {
/// @dev Should return whether the signature provided is valid for the
/// provided data
/// @param _hash Hash of the data to be signed
/// @param _signature Signature byte array associated with _data
///
/// MUST return the bytes4 magic value 0x1626ba7e when function passes.
/// MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for
/// solc > 0.5)
/// MUST allow external calls
///
function isValidSignature(bytes32 _hash, bytes memory _signature)
external
view
returns (bytes4 magicValue);
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.7.6;
pragma abicoder v2;
import "../interfaces/GPv2EIP1271.sol";
import "../interfaces/IERC20.sol";
import "../libraries/GPv2Order.sol";
import "../libraries/GPv2SafeERC20.sol";
import "../libraries/SafeMath.sol";
import "../GPv2Settlement.sol";
/// @title Proof of Concept Smart Order
/// @author Gnosis Developers
contract SmartSellOrder is EIP1271Verifier {
using GPv2Order for GPv2Order.Data;
using GPv2SafeERC20 for IERC20;
using SafeMath for uint256;
bytes32 public constant APPDATA = keccak256("SmartSellOrder");
address public immutable owner;
bytes32 public immutable domainSeparator;
IERC20 public immutable sellToken;
IERC20 public immutable buyToken;
uint256 public immutable totalSellAmount;
uint256 public immutable totalFeeAmount;
uint32 public immutable validTo;
constructor(
GPv2Settlement settlement,
IERC20 sellToken_,
IERC20 buyToken_,
uint32 validTo_,
uint256 totalSellAmount_,
uint256 totalFeeAmount_
) {
owner = msg.sender;
domainSeparator = settlement.domainSeparator();
sellToken = sellToken_;
buyToken = buyToken_;
validTo = validTo_;
totalSellAmount = totalSellAmount_;
totalFeeAmount = totalFeeAmount_;
sellToken_.approve(
address(settlement.vaultRelayer()),
type(uint256).max
);
}
modifier onlyOwner {
require(msg.sender == owner, "not owner");
_;
}
function withdraw(uint256 amount) external onlyOwner {
sellToken.safeTransfer(owner, amount);
}
function close() external onlyOwner {
uint256 balance = sellToken.balanceOf(address(this));
if (balance != 0) {
sellToken.safeTransfer(owner, balance);
}
selfdestruct(payable(owner));
}
function isValidSignature(bytes32 hash, bytes memory signature)
external
view
override
returns (bytes4 magicValue)
{
uint256 sellAmount = abi.decode(signature, (uint256));
GPv2Order.Data memory order = orderForSellAmount(sellAmount);
if (order.hash(domainSeparator) == hash) {
magicValue = GPv2EIP1271.MAGICVALUE;
}
}
function orderForSellAmount(uint256 sellAmount)
public
view
returns (GPv2Order.Data memory order)
{
order.sellToken = sellToken;
order.buyToken = buyToken;
order.receiver = owner;
order.sellAmount = sellAmount;
order.buyAmount = buyAmountForSellAmount(sellAmount);
order.validTo = validTo;
order.appData = APPDATA;
order.feeAmount = totalFeeAmount.mul(sellAmount).div(totalSellAmount);
order.kind = GPv2Order.KIND_SELL;
// NOTE: We counter-intuitively set `partiallyFillable` to `false`, even
// if the smart order as a whole acts like a partially fillable order.
// This is done since, once a settlement commits to a specific sell
// amount, then it is expected to use it completely and not partially.
order.partiallyFillable = false;
order.sellTokenBalance = GPv2Order.BALANCE_ERC20;
order.buyTokenBalance = GPv2Order.BALANCE_ERC20;
}
function buyAmountForSellAmount(uint256 sellAmount)
private
view
returns (uint256 buyAmount)
{
uint256 feeAdjustedBalance =
sellToken.balanceOf(address(this)).mul(totalSellAmount).div(
totalSellAmount.add(totalFeeAmount)
);
uint256 soldAmount =
totalSellAmount > feeAdjustedBalance
? totalSellAmount - feeAdjustedBalance
: 0;
// NOTE: This is currently a silly price strategy where the xrate
// increases linearly from 1:1 to 1:2 as the smart order gets filled.
// This can be extended to more complex "price curves".
buyAmount = sellAmount
.mul(totalSellAmount.add(sellAmount).add(soldAmount))
.div(totalSellAmount);
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.7.6;
import "../libraries/SafeMath.sol";
abstract contract NonStandardERC20 {
using SafeMath for uint256;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
function mint(address to, uint256 amount) external {
balanceOf[to] = balanceOf[to].add(amount);
}
function approve(address spender, uint256 amount) external {
allowance[msg.sender][spender] = amount;
}
function transfer_(address to, uint256 amount) internal {
balanceOf[msg.sender] = balanceOf[msg.sender].sub(amount);
balanceOf[to] = balanceOf[to].add(amount);
}
function transferFrom_(
address from,
address to,
uint256 amount
) internal {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(amount);
balanceOf[from] = balanceOf[from].sub(amount);
balanceOf[to] = balanceOf[to].add(amount);
}
}
contract ERC20NoReturn is NonStandardERC20 {
function transfer(address to, uint256 amount) external {
transfer_(to, amount);
}
function transferFrom(
address from,
address to,
uint256 amount
) external {
transferFrom_(from, to, amount);
}
}
contract ERC20ReturningUint is NonStandardERC20 {
// Largest 256-bit prime :)
uint256 private constant OK =
115792089237316195423570985008687907853269984665640564039457584007913129639747;
function transfer(address to, uint256 amount) external returns (uint256) {
transfer_(to, amount);
return OK;
}
function transferFrom(
address from,
address to,
uint256 amount
) external returns (uint256) {
transferFrom_(from, to, amount);
return OK;
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.7.6;
pragma abicoder v2;
import "../interfaces/IERC20.sol";
import "../libraries/GPv2SafeERC20.sol";
contract GPv2SafeERC20TestInterface {
using GPv2SafeERC20 for IERC20;
function transfer(
IERC20 token,
address to,
uint256 value
) public {
token.safeTransfer(to, value);
}
function transferFrom(
IERC20 token,
address from,
address to,
uint256 value
) public {
token.safeTransferFrom(from, to, value);
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.7.6;
pragma abicoder v2;
import "../libraries/GPv2Order.sol";
import "../libraries/GPv2Trade.sol";
contract GPv2TradeTestInterface {
function extractOrderTest(
IERC20[] calldata tokens,
GPv2Trade.Data calldata trade
) external pure returns (GPv2Order.Data memory order) {
GPv2Trade.extractOrder(trade, tokens, order);
}
function extractFlagsTest(uint256 flags)
external
pure
returns (
bytes32 kind,
bool partiallyFillable,
bytes32 sellTokenBalance,
bytes32 buyTokenBalance,
GPv2Signing.Scheme signingScheme
)
{
return GPv2Trade.extractFlags(flags);
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.7.6;
pragma abicoder v2;
import "../libraries/GPv2Order.sol";
import "../libraries/GPv2Trade.sol";
import "../mixins/GPv2Signing.sol";
contract GPv2SigningTestInterface is GPv2Signing {
function recoverOrderFromTradeTest(
IERC20[] calldata tokens,
GPv2Trade.Data calldata trade
) external view returns (RecoveredOrder memory recoveredOrder) {
recoveredOrder = allocateRecoveredOrder();
recoverOrderFromTrade(recoveredOrder, tokens, trade);
}
function recoverOrderSignerTest(
GPv2Order.Data memory order,
GPv2Signing.Scheme signingScheme,
bytes calldata signature
) external view returns (address owner) {
(, owner) = recoverOrderSigner(order, signingScheme, signature);
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.7.6;
import "../interfaces/GPv2EIP1271.sol";
/// @dev This contract implements the standard described in EIP-1271 with the
/// minor change that the verification function changes the state. This is
/// forbidden by the standard specifications.
contract StateChangingEIP1271 {
uint256 public state = 0;
// solhint-disable-next-line no-unused-vars
function isValidSignature(bytes32 _hash, bytes memory _signature)
public
returns (bytes4 magicValue)
{
state += 1;
magicValue = GPv2EIP1271.MAGICVALUE;
// The following lines are here to suppress no-unused-var compiler-time
// warnings when compiling the contracts. The warning is forwarded by
// Hardhat from Solc. It is currently not possible to selectively
// ignore Solc warinings:
// <https://github.com/ethereum/solidity/issues/269>
_hash;
_signature;
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.7.6;
pragma abicoder v2;
import "../libraries/GPv2Order.sol";
contract GPv2OrderTestInterface {
using GPv2Order for GPv2Order.Data;
using GPv2Order for bytes;
function typeHashTest() external pure returns (bytes32) {
return GPv2Order.TYPE_HASH;
}
function hashTest(GPv2Order.Data memory order, bytes32 domainSeparator)
external
pure
returns (bytes32 orderDigest)
{
orderDigest = order.hash(domainSeparator);
}
function packOrderUidParamsTest(
uint256 bufferLength,
bytes32 orderDigest,
address owner,
uint32 validTo
) external pure returns (bytes memory orderUid) {
orderUid = new bytes(bufferLength);
orderUid.packOrderUidParams(orderDigest, owner, validTo);
}
function extractOrderUidParamsTest(bytes calldata orderUid)
external
pure
returns (
bytes32 orderDigest,
address owner,
uint32 validTo
)
{
return orderUid.extractOrderUidParams();
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.7.6;
pragma abicoder v2;
import "../libraries/GPv2Transfer.sol";
contract GPv2TransferTestInterface {
function fastTransferFromAccountTest(
IVault vault,
GPv2Transfer.Data calldata transfer,
address recipient
) external {
GPv2Transfer.fastTransferFromAccount(vault, transfer, recipient);
}
function transferFromAccountsTest(
IVault vault,
GPv2Transfer.Data[] calldata transfers,
address recipient
) external {
GPv2Transfer.transferFromAccounts(vault, transfers, recipient);
}
function transferToAccountsTest(
IVault vault,
GPv2Transfer.Data[] memory transfers
) external {
GPv2Transfer.transferToAccounts(vault, transfers);
}
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.7.6;
pragma abicoder v2;
import "../GPv2Settlement.sol";
import "../libraries/GPv2Interaction.sol";
import "../libraries/GPv2Trade.sol";
import "../libraries/GPv2Transfer.sol";
contract GPv2SettlementTestInterface is GPv2Settlement {
constructor(GPv2Authentication authenticator_, IVault vault)
GPv2Settlement(authenticator_, vault)
// solhint-disable-next-line no-empty-blocks
{
}
function setFilledAmount(bytes calldata orderUid, uint256 amount) external {
filledAmount[orderUid] = amount;
}
function computeTradeExecutionsTest(
IERC20[] calldata tokens,
uint256[] calldata clearingPrices,
GPv2Trade.Data[] calldata trades
)
external
returns (
GPv2Transfer.Data[] memory inTransfers,
GPv2Transfer.Data[] memory outTransfers
)
{
(inTransfers, outTransfers) = computeTradeExecutions(
tokens,
clearingPrices,
trades
);
}
function computeTradeExecutionMemoryTest() external returns (uint256 mem) {
RecoveredOrder memory recoveredOrder;
GPv2Transfer.Data memory inTransfer;
GPv2Transfer.Data memory outTransfer;
// NOTE: Solidity stores the free memory pointer at address 0x40. Read
// it before and after calling `processOrder` to ensure that there are
// no memory allocations.
// solhint-disable-next-line no-inline-assembly
assembly {
mem := mload(0x40)
}
// solhint-disable-next-line not-rely-on-time
recoveredOrder.data.validTo = uint32(block.timestamp);
computeTradeExecution(recoveredOrder, 1, 1, 0, inTransfer, outTransfer);
// solhint-disable-next-line no-inline-assembly
assembly {
mem := sub(mload(0x40), mem)
}
}
function executeInteractionsTest(
GPv2Interaction.Data[] calldata interactions
) external {
executeInteractions(interactions);
}
function freeFilledAmountStorageTest(bytes[] calldata orderUids) external {
this.freeFilledAmountStorage(orderUids);
}
function freePreSignatureStorageTest(bytes[] calldata orderUids) external {
this.freePreSignatureStorage(orderUids);
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.7.6;
pragma abicoder v2;
import "../libraries/GPv2Interaction.sol";
contract GPv2InteractionTestInterface {
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
function executeTest(GPv2Interaction.Data calldata interaction) external {
GPv2Interaction.execute(interaction);
}
function selectorTest(GPv2Interaction.Data calldata interaction)
external
pure
returns (bytes4)
{
return GPv2Interaction.selector(interaction);
}
}
| NOTE: Solidity stores the free memory pointer at address 0x40. Read it before and after calling `processOrder` to ensure that there are no memory allocations. solhint-disable-next-line no-inline-assembly solhint-disable-next-line no-inline-assembly | function computeTradeExecutionMemoryTest() external returns (uint256 mem) {
RecoveredOrder memory recoveredOrder;
GPv2Transfer.Data memory inTransfer;
GPv2Transfer.Data memory outTransfer;
assembly {
mem := mload(0x40)
}
computeTradeExecution(recoveredOrder, 1, 1, 0, inTransfer, outTransfer);
assembly {
mem := sub(mload(0x40), mem)
}
}
| 6,258,643 | [
1,
17857,
30,
348,
7953,
560,
9064,
326,
4843,
3778,
4407,
622,
1758,
374,
92,
7132,
18,
2720,
518,
1865,
471,
1839,
4440,
1375,
2567,
2448,
68,
358,
3387,
716,
1915,
854,
1158,
3778,
23804,
18,
3704,
11317,
17,
8394,
17,
4285,
17,
1369,
1158,
17,
10047,
17,
28050,
3704,
11317,
17,
8394,
17,
4285,
17,
1369,
1158,
17,
10047,
17,
28050,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
3671,
22583,
3210,
6031,
4709,
1435,
3903,
1135,
261,
11890,
5034,
1663,
13,
288,
203,
3639,
868,
16810,
2448,
3778,
24616,
2448,
31,
203,
3639,
4948,
90,
22,
5912,
18,
751,
3778,
316,
5912,
31,
203,
3639,
4948,
90,
22,
5912,
18,
751,
3778,
596,
5912,
31,
203,
203,
3639,
19931,
288,
203,
5411,
1663,
519,
312,
945,
12,
20,
92,
7132,
13,
203,
3639,
289,
203,
203,
3639,
3671,
22583,
3210,
12,
266,
16810,
2448,
16,
404,
16,
404,
16,
374,
16,
316,
5912,
16,
596,
5912,
1769,
203,
203,
3639,
19931,
288,
203,
5411,
1663,
519,
720,
12,
81,
945,
12,
20,
92,
7132,
3631,
1663,
13,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.6;
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
contract MCBStaking is Initializable, ReentrancyGuardUpgradeable, OwnableUpgradeable {
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
string public constant name = "MCBStaking";
struct StakedBalance {
uint256 balance;
uint256 unlockTime;
}
IERC20Upgradeable public stakeToken;
uint256 public lockPeriod;
mapping(address => StakedBalance) public stakedBalances;
event SetUnlockPeriod(uint256 previousLockPeriod, uint256 newLockPeriod);
event Stake(
address indexed account,
uint256 newStaked,
uint256 totalStaked,
uint256 unlockTime
);
event Redeem(address indexed account, uint256 redeemed);
function initialize(address stakeToken_, uint256 lockPeriod_) external initializer {
__ReentrancyGuard_init();
__Ownable_init();
stakeToken = IERC20Upgradeable(stakeToken_);
_setUnlockPeriod(lockPeriod_);
}
/// @notice Get staked balance of account.
function balanceOf(address account) public view returns (uint256) {
return stakedBalances[account].balance;
}
/// @notice Get timestamp of unlock time.
function unlockTime(address account) public view returns (uint256) {
return stakedBalances[account].unlockTime;
}
/// @notice Get expected unlock time if try to stake 'amount' tokens.
function calcUnlockTime(address account, uint256 amount) public view returns (uint256) {
return _calcUnlockTime(stakedBalances[account], amount);
}
/// @notice Get remaining seconds before unlock.
function secondsUntilUnlock(address account) public view returns (uint256) {
uint256 eta = stakedBalances[account].unlockTime;
uint256 current = _blockTime();
return eta > current ? eta - current : 0;
}
/// @notice Stake token into contract and refresh unlock time according to `_calcUnlockTime`.
function stake(uint256 amount) external nonReentrant {
require(amount != 0, "MCBStaking::stake::ZeroStakeAmount");
StakedBalance storage staked = stakedBalances[msg.sender];
uint256 newUnlockTime = _calcUnlockTime(staked, amount);
stakeToken.transferFrom(msg.sender, address(this), amount);
staked.balance += amount;
staked.unlockTime = newUnlockTime;
emit Stake(msg.sender, amount, staked.balance, staked.unlockTime);
}
/// @notice Refresh unlock time to current time + lockPeriod
function restake() external {
StakedBalance storage staked = stakedBalances[msg.sender];
require(staked.balance != 0, "MCBStaking::restake::NotStakedYet");
staked.unlockTime = _blockTime() + lockPeriod;
emit Stake(msg.sender, 0, staked.balance, staked.unlockTime);
}
/// @notice Redeem token from contract if time has already surpassed the `unlockTime`.
function redeem() external nonReentrant {
StakedBalance storage staked = stakedBalances[msg.sender];
require(staked.balance != 0, "MCBStaking::redeem::NotStaked");
require(_blockTime() >= staked.unlockTime, "MCBStaking::redeem::LockTimeNotSurpassed");
uint256 balance = staked.balance;
staked.balance -= staked.balance;
stakeToken.transfer(msg.sender, balance);
emit Redeem(msg.sender, balance);
}
/// @notice Set new unlock period which only applies on new stakes.
function setUnlockPeriod(uint256 period) external onlyOwner {
_setUnlockPeriod(period);
}
function _setUnlockPeriod(uint256 period) internal {
require(period != lockPeriod, "MCBStaking::_setUnlockPeriod::PeriodUnchanged");
emit SetUnlockPeriod(lockPeriod, period);
lockPeriod = period;
}
function _calcUnlockTime(StakedBalance storage staked, uint256 amount)
internal
view
returns (uint256)
{
uint256 eta = staked.unlockTime;
// protection
if (amount == 0) {
return eta;
}
uint256 current = _blockTime();
uint256 remaining = eta > current ? eta - current : 0;
// if last staking ends, lock all funds in contract by lockPeriod
if (remaining == 0) {
return current + lockPeriod;
}
// else update the unlockTime with (p + nT) / (m + n)
// ref: https://docs.google.com/document/d/1IC4mmb2GnEZ3nDTj1Tq2gypsNpHOZjNFQGncGDnOsRk/edit
return
current +
(staked.balance * remaining + amount * lockPeriod) /
(staked.balance + amount);
}
function _blockTime() internal view virtual returns (uint256) {
return block.timestamp;
}
}
| @notice Refresh unlock time to current time + lockPeriod | function restake() external {
StakedBalance storage staked = stakedBalances[msg.sender];
require(staked.balance != 0, "MCBStaking::restake::NotStakedYet");
staked.unlockTime = _blockTime() + lockPeriod;
emit Stake(msg.sender, 0, staked.balance, staked.unlockTime);
}
| 1,836,264 | [
1,
8323,
7186,
813,
358,
783,
813,
397,
2176,
5027,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
3127,
911,
1435,
3903,
288,
203,
3639,
934,
9477,
13937,
2502,
384,
9477,
273,
384,
9477,
38,
26488,
63,
3576,
18,
15330,
15533,
203,
3639,
2583,
12,
334,
9477,
18,
12296,
480,
374,
16,
315,
49,
8876,
510,
6159,
2866,
8792,
911,
2866,
1248,
510,
9477,
61,
278,
8863,
203,
3639,
384,
9477,
18,
26226,
950,
273,
389,
2629,
950,
1435,
397,
2176,
5027,
31,
203,
3639,
3626,
934,
911,
12,
3576,
18,
15330,
16,
374,
16,
384,
9477,
18,
12296,
16,
384,
9477,
18,
26226,
950,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1313161554/0xEaE47c5D99f7B31165a7f0c5f7E0D6afA25CFd55/sources/IDMMRouter01.sol | @dev full interface for router | interface IDMMRouter01 is IDMMExchangeRouter, IDMMLiquidityRouter {
function factory() external pure returns (address);
function weth() external pure returns (IWETH);
pragma solidity 0.6.12;
}
| 16,916,540 | [
1,
2854,
1560,
364,
4633,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5831,
1599,
8206,
8259,
1611,
353,
1599,
8206,
11688,
8259,
16,
1599,
49,
1495,
18988,
24237,
8259,
288,
203,
565,
445,
3272,
1435,
3903,
16618,
1135,
261,
2867,
1769,
203,
203,
565,
445,
341,
546,
1435,
3903,
16618,
1135,
261,
45,
59,
1584,
44,
1769,
203,
683,
9454,
18035,
560,
374,
18,
26,
18,
2138,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/11155111/0x8dE3a5412ac569B36430658b27baB52F3Df5e555/sources/contracts/swap.sol | / Indicates if the initiated order has been accepted.
| bool orderAccepted; | 3,787,365 | [
1,
19,
18336,
309,
326,
27183,
1353,
711,
2118,
8494,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
1426,
1353,
18047,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
abstract contract stKSM is IERC20, Pausable {
/**
* @dev stKSM balances are dynamic and are calculated based on the accounts' shares
* and the total amount of KSM controlled by the protocol. Account shares aren't
* normalized, so the contract also stores the sum of all shares to calculate
* each account's token balance which equals to:
*
* shares[account] * _getTotalPooledKSM() / _getTotalShares()
*/
mapping (address => uint256) private shares;
/**
* @dev Allowances are nominated in tokens, not token shares.
*/
mapping (address => mapping (address => uint256)) private allowances;
/**
* @dev Storage position used for holding the total amount of shares in existence.
*/
uint256 internal totalShares;
/**
* @return the amount of tokens in existence.
*
* @dev Always equals to `_getTotalPooledKSM()` since token amount
* is pegged to the total amount of KSM controlled by the protocol.
*/
function totalSupply() public view override returns (uint256) {
return _getTotalPooledKSM();
}
/**
* @return the entire amount of KSMs controlled by the protocol.
*
* @dev The sum of all KSM balances in the protocol.
*/
function getTotalPooledKSM() public view returns (uint256) {
return _getTotalPooledKSM();
}
/**
* @return the amount of tokens owned by the `_account`.
*
* @dev Balances are dynamic and equal the `_account`'s share in the amount of the
* total KSM controlled by the protocol. See `sharesOf`.
*/
function balanceOf(address _account) public view override returns (uint256) {
return getPooledKSMByShares(_sharesOf(_account));
}
/**
* @notice Moves `_amount` tokens from the caller's account to the `_recipient` account.
*
* @return a boolean value indicating whether the operation succeeded.
* Emits a `Transfer` event.
*
* Requirements:
*
* - `_recipient` cannot be the zero address.
* - the caller must have a balance of at least `_amount`.
* - the contract must not be paused.
*
* @dev The `_amount` argument is the amount of tokens, not shares.
*/
function transfer(address _recipient, uint256 _amount) public override returns (bool) {
_transfer(msg.sender, _recipient, _amount);
return true;
}
/**
* @return the remaining number of tokens that `_spender` is allowed to spend
* on behalf of `_owner` through `transferFrom`. This is zero by default.
*
* @dev This value changes when `approve` or `transferFrom` is called.
*/
function allowance(address _owner, address _spender) public view override returns (uint256) {
return allowances[_owner][_spender];
}
/**
* @notice Sets `_amount` as the allowance of `_spender` over the caller's tokens.
*
* @return a boolean value indicating whether the operation succeeded.
* Emits an `Approval` event.
*
* Requirements:
*
* - `_spender` cannot be the zero address.
* - the contract must not be paused.
*
* @dev The `_amount` argument is the amount of tokens, not shares.
*/
function approve(address _spender, uint256 _amount) public override returns (bool) {
_approve(msg.sender, _spender, _amount);
return true;
}
/**
* @notice Moves `_amount` tokens from `_sender` to `_recipient` using the
* allowance mechanism. `_amount` is then deducted from the caller's
* allowance.
*
* @return a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `_sender` and `_recipient` cannot be the zero addresses.
* - `_sender` must have a balance of at least `_amount`.
* - the caller must have allowance for `_sender`'s tokens of at least `_amount`.
* - the contract must not be paused.
*
* @dev The `_amount` argument is the amount of tokens, not shares.
*/
function transferFrom(address _sender, address _recipient, uint256 _amount) public override returns (bool) {
uint256 currentAllowance = allowances[_sender][msg.sender];
require(currentAllowance >= _amount, "TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE");
_transfer(_sender, _recipient, _amount);
_approve(_sender, msg.sender, currentAllowance -_amount);
return true;
}
/**
* @notice Atomically increases the allowance granted to `_spender` by the caller by `_addedValue`.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol#L42
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `_spender` cannot be the the zero address.
* - the contract must not be paused.
*/
function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) {
_approve(msg.sender, _spender, allowances[msg.sender][_spender] + _addedValue);
return true;
}
/**
* @notice Atomically decreases the allowance granted to `_spender` by the caller by `_subtractedValue`.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol#L42
* 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`.
* - the contract must not be paused.
*/
function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) {
uint256 currentAllowance = allowances[msg.sender][_spender];
require(currentAllowance >= _subtractedValue, "DECREASED_ALLOWANCE_BELOW_ZERO");
_approve(msg.sender, _spender, currentAllowance-_subtractedValue);
return true;
}
/**
* @return the total amount of shares in existence.
*
* @dev The sum of all accounts' shares can be an arbitrary number, therefore
* it is necessary to store it in order to calculate each account's relative share.
*/
function getTotalShares() public view returns (uint256) {
return _getTotalShares();
}
/**
* @return the amount of shares owned by `_account`.
*/
function sharesOf(address _account) public view returns (uint256) {
return _sharesOf(_account);
}
/**
* @return the amount of shares that corresponds to `_ethAmount` protocol-controlled KSM.
*/
function getSharesByPooledKSM(uint256 _amount) public view returns (uint256) {
uint256 totalPooledKSM = _getTotalPooledKSM();
if (totalPooledKSM == 0) {
return 0;
} else {
return _amount * _getTotalShares() / totalPooledKSM;
}
}
/**
* @return the amount of KSM that corresponds to `_sharesAmount` token shares.
*/
function getPooledKSMByShares(uint256 _sharesAmount) public view returns (uint256) {
uint256 _totalShares = _getTotalShares();
if (totalShares == 0) {
return 0;
} else {
return _sharesAmount * _getTotalPooledKSM() / _totalShares;
}
}
/**
* @return the total amount (in wei) of KSM controlled by the protocol.
* @dev This is used for calaulating tokens from shares and vice versa.
* @dev This function is required to be implemented in a derived contract.
*/
function _getTotalPooledKSM() internal view virtual returns (uint256);
/**
* @notice Moves `_amount` tokens from `_sender` to `_recipient`.
* Emits a `Transfer` event.
*/
function _transfer(address _sender, address _recipient, uint256 _amount) internal {
uint256 _sharesToTransfer = getSharesByPooledKSM(_amount);
_transferShares(_sender, _recipient, _sharesToTransfer);
emit Transfer(_sender, _recipient, _amount);
}
/**
* @notice Sets `_amount` as the allowance of `_spender` over the `_owner` s tokens.
*
* Emits an `Approval` event.
*
* Requirements:
*
* - `_owner` cannot be the zero address.
* - `_spender` cannot be the zero address.
* - the contract must not be paused.
*/
function _approve(address _owner, address _spender, uint256 _amount) internal whenNotPaused {
require(_owner != address(0), "APPROVE_FROM_ZERO_ADDRESS");
require(_spender != address(0), "APPROVE_TO_ZERO_ADDRESS");
allowances[_owner][_spender] = _amount;
emit Approval(_owner, _spender, _amount);
}
/**
* @return the total amount of shares in existence.
*/
function _getTotalShares() internal view returns (uint256) {
return totalShares;
}
/**
* @return the amount of shares owned by `_account`.
*/
function _sharesOf(address _account) internal view returns (uint256) {
return shares[_account];
}
/**
* @notice Moves `_sharesAmount` shares from `_sender` to `_recipient`.
*
* Requirements:
*
* - `_sender` cannot be the zero address.
* - `_recipient` cannot be the zero address.
* - `_sender` must hold at least `_sharesAmount` shares.
* - the contract must not be paused.
*/
function _transferShares(address _sender, address _recipient, uint256 _sharesAmount) internal whenNotPaused {
require(_sender != address(0), "TRANSFER_FROM_THE_ZERO_ADDRESS");
require(_recipient != address(0), "TRANSFER_TO_THE_ZERO_ADDRESS");
uint256 currentSenderShares = shares[_sender];
require(_sharesAmount <= currentSenderShares, "TRANSFER_AMOUNT_EXCEEDS_BALANCE");
shares[_sender] = currentSenderShares - _sharesAmount;
shares[_recipient] = shares[_recipient] + _sharesAmount;
}
/**
* @notice Creates `_sharesAmount` shares and assigns them to `_recipient`, increasing the total amount of shares.
* @dev This doesn't increase the token total supply.
*
* Requirements:
*
* - `_recipient` cannot be the zero address.
* - the contract must not be paused.
*/
function _mintShares(address _recipient, uint256 _sharesAmount) internal whenNotPaused returns (uint256 newTotalShares) {
require(_recipient != address(0), "MINT_TO_THE_ZERO_ADDRESS");
newTotalShares = _getTotalShares() + _sharesAmount;
totalShares = newTotalShares;
shares[_recipient] = shares[_recipient] + _sharesAmount;
// Notice: we're not emitting a Transfer event from the zero address here since shares mint
// works by taking the amount of tokens corresponding to the minted shares from all other
// token holders, proportionally to their share. The total supply of the token doesn't change
// as the result. This is equivalent to performing a send from each other token holder's
// address to `address`, but we cannot reflect this as it would require sending an unbounded
// number of events.
}
/**
* @notice Destroys `_sharesAmount` shares from `_account`'s holdings, decreasing the total amount of shares.
* @dev This doesn't decrease the token total supply.
*
* Requirements:
*
* - `_account` cannot be the zero address.
* - `_account` must hold at least `_sharesAmount` shares.
* - the contract must not be paused.
*/
function _burnShares(address _account, uint256 _sharesAmount) internal whenNotPaused returns (uint256 newTotalShares) {
require(_account != address(0), "BURN_FROM_THE_ZERO_ADDRESS");
uint256 accountShares = shares[_account];
require(_sharesAmount <= accountShares, "BURN_AMOUNT_EXCEEDS_BALANCE");
newTotalShares = _getTotalShares() - _sharesAmount;
totalShares = newTotalShares;
shares[_account] = accountShares - _sharesAmount;
// Notice: we're not emitting a Transfer event to the zero address here since shares burn
// works by redistributing the amount of tokens corresponding to the burned shares between
// all other token holders. The total supply of the token doesn't change as the result.
// This is equivalent to performing a send from `address` to each other token holder address,
// but we cannot reflect this as it would require sending an unbounded number of events.
}
}
| * @notice Sets `_amount` as the allowance of `_spender` over the `_owner` s tokens. Emits an `Approval` event. Requirements: - `_owner` cannot be the zero address. - `_spender` cannot be the zero address. - the contract must not be paused./ | function _approve(address _owner, address _spender, uint256 _amount) internal whenNotPaused {
require(_owner != address(0), "APPROVE_FROM_ZERO_ADDRESS");
require(_spender != address(0), "APPROVE_TO_ZERO_ADDRESS");
allowances[_owner][_spender] = _amount;
emit Approval(_owner, _spender, _amount);
}
| 2,510,488 | [
1,
2785,
1375,
67,
8949,
68,
487,
326,
1699,
1359,
434,
1375,
67,
87,
1302,
264,
68,
1879,
326,
1375,
67,
8443,
68,
272,
2430,
18,
7377,
1282,
392,
1375,
23461,
68,
871,
18,
29076,
30,
300,
1375,
67,
8443,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
67,
87,
1302,
264,
68,
2780,
506,
326,
3634,
1758,
18,
300,
326,
6835,
1297,
486,
506,
17781,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
12908,
537,
12,
2867,
389,
8443,
16,
1758,
389,
87,
1302,
264,
16,
2254,
5034,
389,
8949,
13,
2713,
1347,
1248,
28590,
288,
203,
3639,
2583,
24899,
8443,
480,
1758,
12,
20,
3631,
315,
2203,
3373,
3412,
67,
11249,
67,
24968,
67,
15140,
8863,
203,
3639,
2583,
24899,
87,
1302,
264,
480,
1758,
12,
20,
3631,
315,
2203,
3373,
3412,
67,
4296,
67,
24968,
67,
15140,
8863,
203,
203,
3639,
1699,
6872,
63,
67,
8443,
6362,
67,
87,
1302,
264,
65,
273,
389,
8949,
31,
203,
3639,
3626,
1716,
685,
1125,
24899,
8443,
16,
389,
87,
1302,
264,
16,
389,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/*
____ __ __ __ _
/ __/__ __ ___ / /_ / / ___ / /_ (_)__ __
_\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
/___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
/___/
* Synthetix: YFIRewards.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.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _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.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.
*/
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.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.
*
* 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.6.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);
function mint(address recipient,uint256 amount) external;
/**
* @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.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.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 ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/IRewardDistributionRecipient.sol
pragma solidity ^0.6.0;
contract IRewardDistributionRecipient is Ownable {
address rewardDistribution;
function notifyRewardAmount(uint256 reward) external virtual {}
modifier onlyRewardDistribution() {
require(_msgSender() == rewardDistribution, "Caller is not reward distribution");
_;
}
function setRewardDistribution(address _rewardDistribution)
external
onlyOwner
{
rewardDistribution = _rewardDistribution;
}
}
// File: contracts/CurveRewards.sol
pragma solidity ^0.6.0;
contract LPTokenWrapper {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Token to be staked
IERC20 public stakingToken = IERC20(address(0));
address public devFund = 0x3249f8c62640DC8ae2F4Ed14CD03bCA9C6Af98B2;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
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 {
uint256 _realAmount = amount.mul(97).div(100);
uint256 _taxedAmount = amount.sub(_realAmount);
_totalSupply = _totalSupply.add(_realAmount);
_balances[msg.sender] = _balances[msg.sender].add(_realAmount);
stakingToken.safeTransferFrom(msg.sender, address(this), _realAmount);
stakingToken.safeTransferFrom(msg.sender,devFund,_taxedAmount);
}
function withdraw(uint256 amount) public virtual{
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
stakingToken.safeTransfer(msg.sender, amount);
}
function setBPT(address BPTAddress) internal {
stakingToken = IERC20(BPTAddress);
}
}
interface MultiplierInterface {
function getTotalMultiplier(address account) external view returns (uint256);
}
interface CalculateCycle {
function calculate(uint256 deployedTime,uint256 currentTime,uint256 duration) external view returns(uint256);
}
contract OMGPool is LPTokenWrapper, IRewardDistributionRecipient {
// Token to be rewarded
IERC20 public rewardToken = IERC20(address(0));
IERC20 public multiplierToken = IERC20(address(0));
CalculateCycle public calculateCycle = CalculateCycle(address(0));
uint256 public DURATION = 4 weeks;
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
uint256 public deployedTime;
uint256 public constant napsDiscountRange = 8 hours;
uint256 public constant napsLevelOneCost = 1000 * 1e18;
uint256 public constant napsLevelTwoCost = 2000 * 1e18;
uint256 public constant napsLevelThreeCost = 5000 * 1e18;
uint256 public constant napsLevelFourCost = 10000 * 1e18;
uint256 public constant napsLevelFiveCost = 20000 * 1e18;
uint256 public constant napsLevelSixCost = 30000 *1e18;
uint256 public constant TwoPercentBonus = 2 * 10 ** 16;
uint256 public constant TenPercentBonus = 1 * 10 ** 17;
uint256 public constant TwentyPercentBonus = 2 * 10 ** 17;
uint256 public constant ThirtyPercentBonus = 3 * 10 ** 17;
uint256 public constant FourtyPercentBonus = 4 * 10 ** 17;
uint256 public constant FiftyPercentBonus = 5 * 10 ** 17;
uint256 public constant SixtyPercentBonus = 6 * 10 ** 17;
uint256 public constant SeventyPercentBonus = 7 * 10 ** 17;
uint256 public constant SeventyFivePercentBonus = 75 * 10 ** 16;
uint256 public constant EightyPercentBonus = 8 * 10 ** 17;
uint256 public constant NinetyPercentBonus = 9 * 10 ** 17;
uint256 public constant OneHundredPercentBonus = 1 * 10 ** 18;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
mapping(address => uint256) public spentNAPS;
mapping(address => uint256) public NAPSlevel;
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
event Boost(uint256 level);
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
constructor(address _stakingToken,address _rewardToken,address _multiplierToken,address _calculateCycleAddr) public{
setBPT(_stakingToken);
rewardToken = IERC20(_rewardToken);
multiplierToken = IERC20(_multiplierToken);
calculateCycle = CalculateCycle(_calculateCycleAddr);
deployedTime = block.timestamp;
}
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)
.mul(getTotalMultiplier(account))
.div(1e18)
.add(rewards[account]);
}
// stake visibility is public as overriding LPTokenWrapper's stake() function
function stake(uint256 amount) public override updateReward(msg.sender) {
require(amount > 0, "Cannot stake 0");
super.stake(amount);
emit Staked(msg.sender, amount);
}
function withdraw(uint256 amount) public override updateReward(msg.sender) {
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.mint(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);
}
function setCycleContract(address _cycleContract) public onlyRewardDistribution {
calculateCycle = CalculateCycle(_cycleContract);
}
// naps stuff
function getLevel(address account) external view returns (uint256) {
return NAPSlevel[account];
}
function getSpent(address account) external view returns (uint256) {
return spentNAPS[account];
}
// Returns the number of naps token to boost
function calculateCost(uint256 level) public view returns(uint256) {
uint256 cycles = calculateCycle.calculate(deployedTime,block.timestamp,napsDiscountRange);
// Cap it to 5 times
if(cycles > 5) {
cycles = 5;
}
// // cost = initialCost * (0.9)^cycles = initial cost * (9^cycles)/(10^cycles)
if (level == 1) {
return napsLevelOneCost.mul(9 ** cycles).div(10 ** cycles);
}else if(level == 2) {
return napsLevelTwoCost.mul(9 ** cycles).div(10 ** cycles);
}else if(level == 3) {
return napsLevelThreeCost.mul(9 ** cycles).div(10 ** cycles);
}else if(level == 4) {
return napsLevelFourCost.mul(9 ** cycles).div(10 ** cycles);
}else if(level == 5) {
return napsLevelFiveCost.mul(9 ** cycles).div(10 ** cycles);
}else if(level == 6) {
return napsLevelSixCost.mul(9 ** cycles).div(10 ** cycles);
}
}
function purchase(uint256 level) external {
require(NAPSlevel[msg.sender] <= level,"Cannot downgrade level or same level");
uint256 cost = calculateCost(level);
uint256 finalCost = cost.sub(spentNAPS[msg.sender]);
// Owner dev fund
multiplierToken.safeTransferFrom(msg.sender,devFund,finalCost);
spentNAPS[msg.sender] = spentNAPS[msg.sender].add(finalCost);
NAPSlevel[msg.sender] = level;
emit Boost(level);
}
function getTotalMultiplier(address account) public view returns (uint256) {
// uint256 zzzMultiplier = multiplier.getTotalMultiplier(account);
uint256 napsMultiplier = 0;
if(NAPSlevel[account] == 1) {
napsMultiplier = TenPercentBonus;
}else if(NAPSlevel[account] == 2) {
napsMultiplier = TwentyPercentBonus;
}else if(NAPSlevel[account] == 3) {
napsMultiplier = ThirtyPercentBonus;
}else if(NAPSlevel[account] == 4) {
napsMultiplier = FiftyPercentBonus;
}else if(NAPSlevel[account] == 5) {
napsMultiplier = SeventyFivePercentBonus;
}else if(NAPSlevel[account] == 6) {
napsMultiplier = OneHundredPercentBonus;
}
return napsMultiplier.add(1*10**18);
}
} | Token to be rewarded | contract OMGPool is LPTokenWrapper, IRewardDistributionRecipient {
IERC20 public rewardToken = IERC20(address(0));
IERC20 public multiplierToken = IERC20(address(0));
CalculateCycle public calculateCycle = CalculateCycle(address(0));
uint256 public DURATION = 4 weeks;
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
uint256 public deployedTime;
uint256 public constant napsDiscountRange = 8 hours;
uint256 public constant napsLevelOneCost = 1000 * 1e18;
uint256 public constant napsLevelTwoCost = 2000 * 1e18;
uint256 public constant napsLevelThreeCost = 5000 * 1e18;
uint256 public constant napsLevelFourCost = 10000 * 1e18;
uint256 public constant napsLevelFiveCost = 20000 * 1e18;
uint256 public constant napsLevelSixCost = 30000 *1e18;
uint256 public constant TwoPercentBonus = 2 * 10 ** 16;
uint256 public constant TenPercentBonus = 1 * 10 ** 17;
uint256 public constant TwentyPercentBonus = 2 * 10 ** 17;
uint256 public constant ThirtyPercentBonus = 3 * 10 ** 17;
uint256 public constant FourtyPercentBonus = 4 * 10 ** 17;
uint256 public constant FiftyPercentBonus = 5 * 10 ** 17;
uint256 public constant SixtyPercentBonus = 6 * 10 ** 17;
uint256 public constant SeventyPercentBonus = 7 * 10 ** 17;
uint256 public constant SeventyFivePercentBonus = 75 * 10 ** 16;
uint256 public constant EightyPercentBonus = 8 * 10 ** 17;
uint256 public constant NinetyPercentBonus = 9 * 10 ** 17;
uint256 public constant OneHundredPercentBonus = 1 * 10 ** 18;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
mapping(address => uint256) public spentNAPS;
mapping(address => uint256) public NAPSlevel;
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
event Boost(uint256 level);
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
constructor(address _stakingToken,address _rewardToken,address _multiplierToken,address _calculateCycleAddr) public{
setBPT(_stakingToken);
rewardToken = IERC20(_rewardToken);
multiplierToken = IERC20(_multiplierToken);
calculateCycle = CalculateCycle(_calculateCycleAddr);
deployedTime = block.timestamp;
}
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 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)
.mul(getTotalMultiplier(account))
.div(1e18)
.add(rewards[account]);
}
function stake(uint256 amount) public override updateReward(msg.sender) {
require(amount > 0, "Cannot stake 0");
super.stake(amount);
emit Staked(msg.sender, amount);
}
function withdraw(uint256 amount) public override updateReward(msg.sender) {
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.mint(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
function getReward() public updateReward(msg.sender) {
uint256 reward = earned(msg.sender);
if (reward > 0) {
rewards[msg.sender] = 0;
rewardToken.mint(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);
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);
}
function notifyRewardAmount(uint256 reward)
external
override
onlyRewardDistribution
updateReward(address(0))
{
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(DURATION);
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(DURATION);
}
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(DURATION);
emit RewardAdded(reward);
}
} else {
function setCycleContract(address _cycleContract) public onlyRewardDistribution {
calculateCycle = CalculateCycle(_cycleContract);
}
function getLevel(address account) external view returns (uint256) {
return NAPSlevel[account];
}
function getSpent(address account) external view returns (uint256) {
return spentNAPS[account];
}
function calculateCost(uint256 level) public view returns(uint256) {
uint256 cycles = calculateCycle.calculate(deployedTime,block.timestamp,napsDiscountRange);
if(cycles > 5) {
cycles = 5;
}
if (level == 1) {
return napsLevelOneCost.mul(9 ** cycles).div(10 ** cycles);
return napsLevelTwoCost.mul(9 ** cycles).div(10 ** cycles);
return napsLevelThreeCost.mul(9 ** cycles).div(10 ** cycles);
return napsLevelFourCost.mul(9 ** cycles).div(10 ** cycles);
return napsLevelFiveCost.mul(9 ** cycles).div(10 ** cycles);
return napsLevelSixCost.mul(9 ** cycles).div(10 ** cycles);
}
}
function calculateCost(uint256 level) public view returns(uint256) {
uint256 cycles = calculateCycle.calculate(deployedTime,block.timestamp,napsDiscountRange);
if(cycles > 5) {
cycles = 5;
}
if (level == 1) {
return napsLevelOneCost.mul(9 ** cycles).div(10 ** cycles);
return napsLevelTwoCost.mul(9 ** cycles).div(10 ** cycles);
return napsLevelThreeCost.mul(9 ** cycles).div(10 ** cycles);
return napsLevelFourCost.mul(9 ** cycles).div(10 ** cycles);
return napsLevelFiveCost.mul(9 ** cycles).div(10 ** cycles);
return napsLevelSixCost.mul(9 ** cycles).div(10 ** cycles);
}
}
function calculateCost(uint256 level) public view returns(uint256) {
uint256 cycles = calculateCycle.calculate(deployedTime,block.timestamp,napsDiscountRange);
if(cycles > 5) {
cycles = 5;
}
if (level == 1) {
return napsLevelOneCost.mul(9 ** cycles).div(10 ** cycles);
return napsLevelTwoCost.mul(9 ** cycles).div(10 ** cycles);
return napsLevelThreeCost.mul(9 ** cycles).div(10 ** cycles);
return napsLevelFourCost.mul(9 ** cycles).div(10 ** cycles);
return napsLevelFiveCost.mul(9 ** cycles).div(10 ** cycles);
return napsLevelSixCost.mul(9 ** cycles).div(10 ** cycles);
}
}
}else if(level == 2) {
}else if(level == 3) {
}else if(level == 4) {
}else if(level == 5) {
}else if(level == 6) {
function purchase(uint256 level) external {
require(NAPSlevel[msg.sender] <= level,"Cannot downgrade level or same level");
uint256 cost = calculateCost(level);
uint256 finalCost = cost.sub(spentNAPS[msg.sender]);
multiplierToken.safeTransferFrom(msg.sender,devFund,finalCost);
spentNAPS[msg.sender] = spentNAPS[msg.sender].add(finalCost);
NAPSlevel[msg.sender] = level;
emit Boost(level);
}
function getTotalMultiplier(address account) public view returns (uint256) {
uint256 napsMultiplier = 0;
if(NAPSlevel[account] == 1) {
napsMultiplier = TenPercentBonus;
napsMultiplier = TwentyPercentBonus;
napsMultiplier = ThirtyPercentBonus;
napsMultiplier = FiftyPercentBonus;
napsMultiplier = SeventyFivePercentBonus;
napsMultiplier = OneHundredPercentBonus;
}
return napsMultiplier.add(1*10**18);
}
function getTotalMultiplier(address account) public view returns (uint256) {
uint256 napsMultiplier = 0;
if(NAPSlevel[account] == 1) {
napsMultiplier = TenPercentBonus;
napsMultiplier = TwentyPercentBonus;
napsMultiplier = ThirtyPercentBonus;
napsMultiplier = FiftyPercentBonus;
napsMultiplier = SeventyFivePercentBonus;
napsMultiplier = OneHundredPercentBonus;
}
return napsMultiplier.add(1*10**18);
}
}else if(NAPSlevel[account] == 2) {
}else if(NAPSlevel[account] == 3) {
}else if(NAPSlevel[account] == 4) {
}else if(NAPSlevel[account] == 5) {
}else if(NAPSlevel[account] == 6) {
} | 42,917 | [
1,
1345,
358,
506,
283,
11804,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
28839,
43,
2864,
353,
511,
52,
1345,
3611,
16,
15908,
359,
1060,
9003,
18241,
288,
203,
565,
467,
654,
39,
3462,
1071,
19890,
1345,
273,
467,
654,
39,
3462,
12,
2867,
12,
20,
10019,
203,
565,
467,
654,
39,
3462,
1071,
15027,
1345,
273,
467,
654,
39,
3462,
12,
2867,
12,
20,
10019,
203,
565,
9029,
13279,
1071,
4604,
13279,
273,
9029,
13279,
12,
2867,
12,
20,
10019,
203,
565,
2254,
5034,
1071,
31794,
273,
1059,
17314,
31,
203,
203,
565,
2254,
5034,
1071,
3879,
11641,
273,
374,
31,
203,
565,
2254,
5034,
1071,
19890,
4727,
273,
374,
31,
203,
565,
2254,
5034,
1071,
1142,
1891,
950,
31,
203,
565,
2254,
5034,
1071,
19890,
2173,
1345,
18005,
31,
203,
565,
2254,
5034,
1071,
19357,
950,
31,
203,
565,
2254,
5034,
1071,
5381,
290,
6679,
9866,
2655,
273,
1725,
7507,
31,
203,
565,
2254,
5034,
1071,
5381,
290,
6679,
2355,
3335,
8018,
273,
4336,
380,
404,
73,
2643,
31,
203,
565,
2254,
5034,
1071,
5381,
290,
6679,
2355,
11710,
8018,
273,
16291,
380,
404,
73,
2643,
31,
203,
565,
2254,
5034,
1071,
5381,
290,
6679,
2355,
28019,
8018,
273,
20190,
380,
404,
73,
2643,
31,
203,
565,
2254,
5034,
1071,
5381,
290,
6679,
2355,
42,
477,
8018,
273,
12619,
380,
404,
73,
2643,
31,
203,
565,
2254,
5034,
1071,
5381,
290,
6679,
2355,
42,
688,
8018,
273,
576,
2787,
380,
404,
73,
2643,
31,
203,
565,
2254,
5034,
1071,
5381,
290,
6679,
2355,
55,
697,
8018,
273,
890,
2787,
380,
21,
73,
2643,
31,
2
]
|
./partial_match/1/0xDE0EeEc80aBe4eeec1f9Df58894F4925E466d8aD/sources/SatoshiVitalikCzBillyCharles.sol | addresses limits status flags | contract SatoshiVitalikCzBillyCharles is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable router;
address public immutable uniswapV2Pair;
address public devWallet;
address private marketingWallet;
uint256 private maxBuyAmount;
uint256 private maxSellAmount;
uint256 private maxWalletAmount;
uint256 private thresholdSwapAmount;
bool private isTrading = false;
bool public swapEnabled = false;
bool public isSwapping;
struct Fees {
uint8 buyTotalFees;
uint8 buyMarketingFee;
uint8 buyDevFee;
uint8 buyLiquidityFee;
uint8 sellTotalFees;
uint8 sellMarketingFee;
uint8 sellDevFee;
uint8 sellLiquidityFee;
}
Fees public _fees = Fees({
buyTotalFees: 0,
buyMarketingFee: 0,
buyDevFee:0,
buyLiquidityFee: 0,
sellTotalFees: 0,
sellMarketingFee: 0,
sellDevFee:0,
sellLiquidityFee: 0
});
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
uint256 private taxTill;
mapping(address => bool) public _isExcludedMaxTransactionAmount;
mapping(address => bool) public _isExcludedMaxWalletAmount;
mapping(address => bool) public _isBlacklisted;
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived
);
mapping(address => bool) private _isExcludedFromFees;
mapping(address => bool) public marketPair;
constructor() ERC20("SatoshiVitalikCzBillyCharles.", "SVCBC") {
router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(router.factory()).createPair(address(this), router.WETH());
_isExcludedMaxTransactionAmount[address(router)] = true;
_isExcludedMaxTransactionAmount[address(uniswapV2Pair)] = true;
_isExcludedMaxTransactionAmount[owner()] = true;
_isExcludedMaxTransactionAmount[address(this)] = true;
_isExcludedFromFees[owner()] = true;
_isExcludedFromFees[address(this)] = true;
_isExcludedMaxWalletAmount[owner()] = true;
_isExcludedMaxWalletAmount[address(this)] = true;
_isExcludedMaxWalletAmount[address(uniswapV2Pair)] = true;
marketPair[address(uniswapV2Pair)] = true;
approve(address(router), type(uint256).max);
uint256 totalSupply = 1e9 * 1e18;
_fees.buyMarketingFee = 2;
_fees.buyLiquidityFee = 1;
_fees.buyDevFee = 1;
_fees.buyTotalFees = _fees.buyMarketingFee + _fees.buyLiquidityFee + _fees.buyDevFee;
_fees.sellMarketingFee = 2;
_fees.sellLiquidityFee = 1;
_fees.sellDevFee = 1;
_fees.sellTotalFees = _fees.sellMarketingFee + _fees.sellLiquidityFee + _fees.sellDevFee;
marketingWallet = address(0xD0fBC11e195F3Ed1AFf137f3EA171888067A226B);
devWallet = address(0xD0fBC11e195F3Ed1AFf137f3EA171888067A226B);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
function swapTrading() external onlyOwner {
isTrading = true;
swapEnabled = true;
taxTill = block.number + 3;
}
function updateThresholdSwapAmount(uint256 newAmount) external onlyOwner returns(bool){
thresholdSwapAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newMaxBuy, uint256 newMaxSell) external onlyOwner {
require(((totalSupply() * newMaxBuy) / 1000) >= (totalSupply() / 100), "maxBuyAmount must be higher than 1%");
require(((totalSupply() * newMaxSell) / 1000) >= (totalSupply() / 100), "maxSellAmount must be higher than 1%");
maxBuyAmount = (totalSupply() * newMaxBuy) / 1000;
maxSellAmount = (totalSupply() * newMaxSell) / 1000;
}
function updateMaxWalletAmount(uint256 newPercentage) external onlyOwner {
require(((totalSupply() * newPercentage) / 1000) >= (totalSupply() / 100), "Cannot set maxWallet lower than 1%");
maxWalletAmount = (totalSupply() * newPercentage) / 1000;
}
function toggleSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function blacklistAddress(address account, bool value) external onlyOwner{
_isBlacklisted[account] = value;
}
function updateFees(uint8 _marketingFeeBuy, uint8 _liquidityFeeBuy,uint8 _devFeeBuy,uint8 _marketingFeeSell, uint8 _liquidityFeeSell,uint8 _devFeeSell) external onlyOwner{
_fees.buyMarketingFee = _marketingFeeBuy;
_fees.buyLiquidityFee = _liquidityFeeBuy;
_fees.buyDevFee = _devFeeBuy;
_fees.buyTotalFees = _fees.buyMarketingFee + _fees.buyLiquidityFee + _fees.buyDevFee;
_fees.sellMarketingFee = _marketingFeeSell;
_fees.sellLiquidityFee = _liquidityFeeSell;
_fees.sellDevFee = _devFeeSell;
_fees.sellTotalFees = _fees.sellMarketingFee + _fees.sellLiquidityFee + _fees.sellDevFee;
require(_fees.buyTotalFees <= 30, "Must keep fees at 30% or less");
require(_fees.sellTotalFees <= 30, "Must keep fees at 30% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
}
function excludeFromWalletLimit(address account, bool excluded) public onlyOwner {
_isExcludedMaxWalletAmount[account] = excluded;
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
function setMarketPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "Must keep uniswapV2Pair");
marketPair[pair] = value;
}
function setWallets(address _marketingWallet,address _devWallet) external onlyOwner{
marketingWallet = _marketingWallet;
devWallet = _devWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (amount == 0) {
super._transfer(sender, recipient, 0);
return;
}
if (
sender != owner() &&
recipient != owner() &&
!isSwapping
) {
if (!isTrading) {
require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active.");
}
if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) {
require(amount <= maxBuyAmount, "buy transfer over max amount");
}
else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) {
require(amount <= maxSellAmount, "Sell transfer over max amount");
}
if (!_isExcludedMaxWalletAmount[recipient]) {
require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded");
}
require(!_isBlacklisted[sender] && !_isBlacklisted[recipient], "Blacklisted address");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= thresholdSwapAmount;
if (
canSwap &&
swapEnabled &&
!isSwapping &&
marketPair[recipient] &&
!_isExcludedFromFees[sender] &&
!_isExcludedFromFees[recipient]
) {
isSwapping = true;
swapBack();
isSwapping = false;
}
bool takeFee = !isSwapping;
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = 0;
if(block.number < taxTill) {
fees = amount.mul(99).div(100);
tokensForMarketing += (fees * 94) / 99;
tokensForDev += (fees * 5) / 99;
fees = amount.mul(_fees.sellTotalFees).div(100);
tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees;
tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees;
tokensForDev += fees * _fees.sellDevFee / _fees.sellTotalFees;
}
else if (marketPair[sender] && _fees.buyTotalFees > 0) {
fees = amount.mul(_fees.buyTotalFees).div(100);
tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees;
tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees;
tokensForDev += fees * _fees.buyDevFee / _fees.buyTotalFees;
}
if (fees > 0) {
super._transfer(sender, address(this), fees);
}
amount -= fees;
}
super._transfer(sender, recipient, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (amount == 0) {
super._transfer(sender, recipient, 0);
return;
}
if (
sender != owner() &&
recipient != owner() &&
!isSwapping
) {
if (!isTrading) {
require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active.");
}
if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) {
require(amount <= maxBuyAmount, "buy transfer over max amount");
}
else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) {
require(amount <= maxSellAmount, "Sell transfer over max amount");
}
if (!_isExcludedMaxWalletAmount[recipient]) {
require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded");
}
require(!_isBlacklisted[sender] && !_isBlacklisted[recipient], "Blacklisted address");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= thresholdSwapAmount;
if (
canSwap &&
swapEnabled &&
!isSwapping &&
marketPair[recipient] &&
!_isExcludedFromFees[sender] &&
!_isExcludedFromFees[recipient]
) {
isSwapping = true;
swapBack();
isSwapping = false;
}
bool takeFee = !isSwapping;
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = 0;
if(block.number < taxTill) {
fees = amount.mul(99).div(100);
tokensForMarketing += (fees * 94) / 99;
tokensForDev += (fees * 5) / 99;
fees = amount.mul(_fees.sellTotalFees).div(100);
tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees;
tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees;
tokensForDev += fees * _fees.sellDevFee / _fees.sellTotalFees;
}
else if (marketPair[sender] && _fees.buyTotalFees > 0) {
fees = amount.mul(_fees.buyTotalFees).div(100);
tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees;
tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees;
tokensForDev += fees * _fees.buyDevFee / _fees.buyTotalFees;
}
if (fees > 0) {
super._transfer(sender, address(this), fees);
}
amount -= fees;
}
super._transfer(sender, recipient, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (amount == 0) {
super._transfer(sender, recipient, 0);
return;
}
if (
sender != owner() &&
recipient != owner() &&
!isSwapping
) {
if (!isTrading) {
require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active.");
}
if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) {
require(amount <= maxBuyAmount, "buy transfer over max amount");
}
else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) {
require(amount <= maxSellAmount, "Sell transfer over max amount");
}
if (!_isExcludedMaxWalletAmount[recipient]) {
require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded");
}
require(!_isBlacklisted[sender] && !_isBlacklisted[recipient], "Blacklisted address");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= thresholdSwapAmount;
if (
canSwap &&
swapEnabled &&
!isSwapping &&
marketPair[recipient] &&
!_isExcludedFromFees[sender] &&
!_isExcludedFromFees[recipient]
) {
isSwapping = true;
swapBack();
isSwapping = false;
}
bool takeFee = !isSwapping;
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = 0;
if(block.number < taxTill) {
fees = amount.mul(99).div(100);
tokensForMarketing += (fees * 94) / 99;
tokensForDev += (fees * 5) / 99;
fees = amount.mul(_fees.sellTotalFees).div(100);
tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees;
tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees;
tokensForDev += fees * _fees.sellDevFee / _fees.sellTotalFees;
}
else if (marketPair[sender] && _fees.buyTotalFees > 0) {
fees = amount.mul(_fees.buyTotalFees).div(100);
tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees;
tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees;
tokensForDev += fees * _fees.buyDevFee / _fees.buyTotalFees;
}
if (fees > 0) {
super._transfer(sender, address(this), fees);
}
amount -= fees;
}
super._transfer(sender, recipient, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (amount == 0) {
super._transfer(sender, recipient, 0);
return;
}
if (
sender != owner() &&
recipient != owner() &&
!isSwapping
) {
if (!isTrading) {
require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active.");
}
if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) {
require(amount <= maxBuyAmount, "buy transfer over max amount");
}
else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) {
require(amount <= maxSellAmount, "Sell transfer over max amount");
}
if (!_isExcludedMaxWalletAmount[recipient]) {
require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded");
}
require(!_isBlacklisted[sender] && !_isBlacklisted[recipient], "Blacklisted address");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= thresholdSwapAmount;
if (
canSwap &&
swapEnabled &&
!isSwapping &&
marketPair[recipient] &&
!_isExcludedFromFees[sender] &&
!_isExcludedFromFees[recipient]
) {
isSwapping = true;
swapBack();
isSwapping = false;
}
bool takeFee = !isSwapping;
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = 0;
if(block.number < taxTill) {
fees = amount.mul(99).div(100);
tokensForMarketing += (fees * 94) / 99;
tokensForDev += (fees * 5) / 99;
fees = amount.mul(_fees.sellTotalFees).div(100);
tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees;
tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees;
tokensForDev += fees * _fees.sellDevFee / _fees.sellTotalFees;
}
else if (marketPair[sender] && _fees.buyTotalFees > 0) {
fees = amount.mul(_fees.buyTotalFees).div(100);
tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees;
tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees;
tokensForDev += fees * _fees.buyDevFee / _fees.buyTotalFees;
}
if (fees > 0) {
super._transfer(sender, address(this), fees);
}
amount -= fees;
}
super._transfer(sender, recipient, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (amount == 0) {
super._transfer(sender, recipient, 0);
return;
}
if (
sender != owner() &&
recipient != owner() &&
!isSwapping
) {
if (!isTrading) {
require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active.");
}
if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) {
require(amount <= maxBuyAmount, "buy transfer over max amount");
}
else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) {
require(amount <= maxSellAmount, "Sell transfer over max amount");
}
if (!_isExcludedMaxWalletAmount[recipient]) {
require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded");
}
require(!_isBlacklisted[sender] && !_isBlacklisted[recipient], "Blacklisted address");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= thresholdSwapAmount;
if (
canSwap &&
swapEnabled &&
!isSwapping &&
marketPair[recipient] &&
!_isExcludedFromFees[sender] &&
!_isExcludedFromFees[recipient]
) {
isSwapping = true;
swapBack();
isSwapping = false;
}
bool takeFee = !isSwapping;
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = 0;
if(block.number < taxTill) {
fees = amount.mul(99).div(100);
tokensForMarketing += (fees * 94) / 99;
tokensForDev += (fees * 5) / 99;
fees = amount.mul(_fees.sellTotalFees).div(100);
tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees;
tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees;
tokensForDev += fees * _fees.sellDevFee / _fees.sellTotalFees;
}
else if (marketPair[sender] && _fees.buyTotalFees > 0) {
fees = amount.mul(_fees.buyTotalFees).div(100);
tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees;
tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees;
tokensForDev += fees * _fees.buyDevFee / _fees.buyTotalFees;
}
if (fees > 0) {
super._transfer(sender, address(this), fees);
}
amount -= fees;
}
super._transfer(sender, recipient, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (amount == 0) {
super._transfer(sender, recipient, 0);
return;
}
if (
sender != owner() &&
recipient != owner() &&
!isSwapping
) {
if (!isTrading) {
require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active.");
}
if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) {
require(amount <= maxBuyAmount, "buy transfer over max amount");
}
else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) {
require(amount <= maxSellAmount, "Sell transfer over max amount");
}
if (!_isExcludedMaxWalletAmount[recipient]) {
require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded");
}
require(!_isBlacklisted[sender] && !_isBlacklisted[recipient], "Blacklisted address");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= thresholdSwapAmount;
if (
canSwap &&
swapEnabled &&
!isSwapping &&
marketPair[recipient] &&
!_isExcludedFromFees[sender] &&
!_isExcludedFromFees[recipient]
) {
isSwapping = true;
swapBack();
isSwapping = false;
}
bool takeFee = !isSwapping;
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = 0;
if(block.number < taxTill) {
fees = amount.mul(99).div(100);
tokensForMarketing += (fees * 94) / 99;
tokensForDev += (fees * 5) / 99;
fees = amount.mul(_fees.sellTotalFees).div(100);
tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees;
tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees;
tokensForDev += fees * _fees.sellDevFee / _fees.sellTotalFees;
}
else if (marketPair[sender] && _fees.buyTotalFees > 0) {
fees = amount.mul(_fees.buyTotalFees).div(100);
tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees;
tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees;
tokensForDev += fees * _fees.buyDevFee / _fees.buyTotalFees;
}
if (fees > 0) {
super._transfer(sender, address(this), fees);
}
amount -= fees;
}
super._transfer(sender, recipient, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (amount == 0) {
super._transfer(sender, recipient, 0);
return;
}
if (
sender != owner() &&
recipient != owner() &&
!isSwapping
) {
if (!isTrading) {
require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active.");
}
if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) {
require(amount <= maxBuyAmount, "buy transfer over max amount");
}
else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) {
require(amount <= maxSellAmount, "Sell transfer over max amount");
}
if (!_isExcludedMaxWalletAmount[recipient]) {
require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded");
}
require(!_isBlacklisted[sender] && !_isBlacklisted[recipient], "Blacklisted address");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= thresholdSwapAmount;
if (
canSwap &&
swapEnabled &&
!isSwapping &&
marketPair[recipient] &&
!_isExcludedFromFees[sender] &&
!_isExcludedFromFees[recipient]
) {
isSwapping = true;
swapBack();
isSwapping = false;
}
bool takeFee = !isSwapping;
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = 0;
if(block.number < taxTill) {
fees = amount.mul(99).div(100);
tokensForMarketing += (fees * 94) / 99;
tokensForDev += (fees * 5) / 99;
fees = amount.mul(_fees.sellTotalFees).div(100);
tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees;
tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees;
tokensForDev += fees * _fees.sellDevFee / _fees.sellTotalFees;
}
else if (marketPair[sender] && _fees.buyTotalFees > 0) {
fees = amount.mul(_fees.buyTotalFees).div(100);
tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees;
tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees;
tokensForDev += fees * _fees.buyDevFee / _fees.buyTotalFees;
}
if (fees > 0) {
super._transfer(sender, address(this), fees);
}
amount -= fees;
}
super._transfer(sender, recipient, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (amount == 0) {
super._transfer(sender, recipient, 0);
return;
}
if (
sender != owner() &&
recipient != owner() &&
!isSwapping
) {
if (!isTrading) {
require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active.");
}
if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) {
require(amount <= maxBuyAmount, "buy transfer over max amount");
}
else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) {
require(amount <= maxSellAmount, "Sell transfer over max amount");
}
if (!_isExcludedMaxWalletAmount[recipient]) {
require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded");
}
require(!_isBlacklisted[sender] && !_isBlacklisted[recipient], "Blacklisted address");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= thresholdSwapAmount;
if (
canSwap &&
swapEnabled &&
!isSwapping &&
marketPair[recipient] &&
!_isExcludedFromFees[sender] &&
!_isExcludedFromFees[recipient]
) {
isSwapping = true;
swapBack();
isSwapping = false;
}
bool takeFee = !isSwapping;
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = 0;
if(block.number < taxTill) {
fees = amount.mul(99).div(100);
tokensForMarketing += (fees * 94) / 99;
tokensForDev += (fees * 5) / 99;
fees = amount.mul(_fees.sellTotalFees).div(100);
tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees;
tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees;
tokensForDev += fees * _fees.sellDevFee / _fees.sellTotalFees;
}
else if (marketPair[sender] && _fees.buyTotalFees > 0) {
fees = amount.mul(_fees.buyTotalFees).div(100);
tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees;
tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees;
tokensForDev += fees * _fees.buyDevFee / _fees.buyTotalFees;
}
if (fees > 0) {
super._transfer(sender, address(this), fees);
}
amount -= fees;
}
super._transfer(sender, recipient, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (amount == 0) {
super._transfer(sender, recipient, 0);
return;
}
if (
sender != owner() &&
recipient != owner() &&
!isSwapping
) {
if (!isTrading) {
require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active.");
}
if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) {
require(amount <= maxBuyAmount, "buy transfer over max amount");
}
else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) {
require(amount <= maxSellAmount, "Sell transfer over max amount");
}
if (!_isExcludedMaxWalletAmount[recipient]) {
require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded");
}
require(!_isBlacklisted[sender] && !_isBlacklisted[recipient], "Blacklisted address");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= thresholdSwapAmount;
if (
canSwap &&
swapEnabled &&
!isSwapping &&
marketPair[recipient] &&
!_isExcludedFromFees[sender] &&
!_isExcludedFromFees[recipient]
) {
isSwapping = true;
swapBack();
isSwapping = false;
}
bool takeFee = !isSwapping;
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = 0;
if(block.number < taxTill) {
fees = amount.mul(99).div(100);
tokensForMarketing += (fees * 94) / 99;
tokensForDev += (fees * 5) / 99;
fees = amount.mul(_fees.sellTotalFees).div(100);
tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees;
tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees;
tokensForDev += fees * _fees.sellDevFee / _fees.sellTotalFees;
}
else if (marketPair[sender] && _fees.buyTotalFees > 0) {
fees = amount.mul(_fees.buyTotalFees).div(100);
tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees;
tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees;
tokensForDev += fees * _fees.buyDevFee / _fees.buyTotalFees;
}
if (fees > 0) {
super._transfer(sender, address(this), fees);
}
amount -= fees;
}
super._transfer(sender, recipient, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (amount == 0) {
super._transfer(sender, recipient, 0);
return;
}
if (
sender != owner() &&
recipient != owner() &&
!isSwapping
) {
if (!isTrading) {
require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active.");
}
if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) {
require(amount <= maxBuyAmount, "buy transfer over max amount");
}
else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) {
require(amount <= maxSellAmount, "Sell transfer over max amount");
}
if (!_isExcludedMaxWalletAmount[recipient]) {
require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded");
}
require(!_isBlacklisted[sender] && !_isBlacklisted[recipient], "Blacklisted address");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= thresholdSwapAmount;
if (
canSwap &&
swapEnabled &&
!isSwapping &&
marketPair[recipient] &&
!_isExcludedFromFees[sender] &&
!_isExcludedFromFees[recipient]
) {
isSwapping = true;
swapBack();
isSwapping = false;
}
bool takeFee = !isSwapping;
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = 0;
if(block.number < taxTill) {
fees = amount.mul(99).div(100);
tokensForMarketing += (fees * 94) / 99;
tokensForDev += (fees * 5) / 99;
fees = amount.mul(_fees.sellTotalFees).div(100);
tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees;
tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees;
tokensForDev += fees * _fees.sellDevFee / _fees.sellTotalFees;
}
else if (marketPair[sender] && _fees.buyTotalFees > 0) {
fees = amount.mul(_fees.buyTotalFees).div(100);
tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees;
tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees;
tokensForDev += fees * _fees.buyDevFee / _fees.buyTotalFees;
}
if (fees > 0) {
super._transfer(sender, address(this), fees);
}
amount -= fees;
}
super._transfer(sender, recipient, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (amount == 0) {
super._transfer(sender, recipient, 0);
return;
}
if (
sender != owner() &&
recipient != owner() &&
!isSwapping
) {
if (!isTrading) {
require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active.");
}
if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) {
require(amount <= maxBuyAmount, "buy transfer over max amount");
}
else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) {
require(amount <= maxSellAmount, "Sell transfer over max amount");
}
if (!_isExcludedMaxWalletAmount[recipient]) {
require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded");
}
require(!_isBlacklisted[sender] && !_isBlacklisted[recipient], "Blacklisted address");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= thresholdSwapAmount;
if (
canSwap &&
swapEnabled &&
!isSwapping &&
marketPair[recipient] &&
!_isExcludedFromFees[sender] &&
!_isExcludedFromFees[recipient]
) {
isSwapping = true;
swapBack();
isSwapping = false;
}
bool takeFee = !isSwapping;
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = 0;
if(block.number < taxTill) {
fees = amount.mul(99).div(100);
tokensForMarketing += (fees * 94) / 99;
tokensForDev += (fees * 5) / 99;
fees = amount.mul(_fees.sellTotalFees).div(100);
tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees;
tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees;
tokensForDev += fees * _fees.sellDevFee / _fees.sellTotalFees;
}
else if (marketPair[sender] && _fees.buyTotalFees > 0) {
fees = amount.mul(_fees.buyTotalFees).div(100);
tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees;
tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees;
tokensForDev += fees * _fees.buyDevFee / _fees.buyTotalFees;
}
if (fees > 0) {
super._transfer(sender, address(this), fees);
}
amount -= fees;
}
super._transfer(sender, recipient, amount);
}
} else if (marketPair[recipient] && _fees.sellTotalFees > 0) {
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (amount == 0) {
super._transfer(sender, recipient, 0);
return;
}
if (
sender != owner() &&
recipient != owner() &&
!isSwapping
) {
if (!isTrading) {
require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active.");
}
if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) {
require(amount <= maxBuyAmount, "buy transfer over max amount");
}
else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) {
require(amount <= maxSellAmount, "Sell transfer over max amount");
}
if (!_isExcludedMaxWalletAmount[recipient]) {
require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded");
}
require(!_isBlacklisted[sender] && !_isBlacklisted[recipient], "Blacklisted address");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= thresholdSwapAmount;
if (
canSwap &&
swapEnabled &&
!isSwapping &&
marketPair[recipient] &&
!_isExcludedFromFees[sender] &&
!_isExcludedFromFees[recipient]
) {
isSwapping = true;
swapBack();
isSwapping = false;
}
bool takeFee = !isSwapping;
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = 0;
if(block.number < taxTill) {
fees = amount.mul(99).div(100);
tokensForMarketing += (fees * 94) / 99;
tokensForDev += (fees * 5) / 99;
fees = amount.mul(_fees.sellTotalFees).div(100);
tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees;
tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees;
tokensForDev += fees * _fees.sellDevFee / _fees.sellTotalFees;
}
else if (marketPair[sender] && _fees.buyTotalFees > 0) {
fees = amount.mul(_fees.buyTotalFees).div(100);
tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees;
tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees;
tokensForDev += fees * _fees.buyDevFee / _fees.buyTotalFees;
}
if (fees > 0) {
super._transfer(sender, address(this), fees);
}
amount -= fees;
}
super._transfer(sender, recipient, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (amount == 0) {
super._transfer(sender, recipient, 0);
return;
}
if (
sender != owner() &&
recipient != owner() &&
!isSwapping
) {
if (!isTrading) {
require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active.");
}
if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) {
require(amount <= maxBuyAmount, "buy transfer over max amount");
}
else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) {
require(amount <= maxSellAmount, "Sell transfer over max amount");
}
if (!_isExcludedMaxWalletAmount[recipient]) {
require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded");
}
require(!_isBlacklisted[sender] && !_isBlacklisted[recipient], "Blacklisted address");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= thresholdSwapAmount;
if (
canSwap &&
swapEnabled &&
!isSwapping &&
marketPair[recipient] &&
!_isExcludedFromFees[sender] &&
!_isExcludedFromFees[recipient]
) {
isSwapping = true;
swapBack();
isSwapping = false;
}
bool takeFee = !isSwapping;
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = 0;
if(block.number < taxTill) {
fees = amount.mul(99).div(100);
tokensForMarketing += (fees * 94) / 99;
tokensForDev += (fees * 5) / 99;
fees = amount.mul(_fees.sellTotalFees).div(100);
tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees;
tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees;
tokensForDev += fees * _fees.sellDevFee / _fees.sellTotalFees;
}
else if (marketPair[sender] && _fees.buyTotalFees > 0) {
fees = amount.mul(_fees.buyTotalFees).div(100);
tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees;
tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees;
tokensForDev += fees * _fees.buyDevFee / _fees.buyTotalFees;
}
if (fees > 0) {
super._transfer(sender, address(this), fees);
}
amount -= fees;
}
super._transfer(sender, recipient, amount);
}
function swapTokensForEth(uint256 tAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = router.WETH();
_approve(address(this), address(router), tAmount);
router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tAmount,
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tAmount, uint256 ethAmount) private {
_approve(address(this), address(router), tAmount);
}
router.addLiquidityETH{ value: ethAmount } (address(this), tAmount, 0, 0 , address(this), block.timestamp);
function swapBack() private {
uint256 contractTokenBalance = balanceOf(address(this));
uint256 toSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if (contractTokenBalance > thresholdSwapAmount * 20) {
contractTokenBalance = thresholdSwapAmount * 20;
}
uint256 amountToSwapForETH = contractTokenBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 newBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = newBalance.mul(tokensForMarketing).div(toSwap);
uint256 ethForDev = newBalance.mul(tokensForDev).div(toSwap);
uint256 ethForLiquidity = newBalance - (ethForMarketing + ethForDev);
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity);
}
}
if (contractTokenBalance == 0 || toSwap == 0) { return; }
function swapBack() private {
uint256 contractTokenBalance = balanceOf(address(this));
uint256 toSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if (contractTokenBalance > thresholdSwapAmount * 20) {
contractTokenBalance = thresholdSwapAmount * 20;
}
uint256 amountToSwapForETH = contractTokenBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 newBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = newBalance.mul(tokensForMarketing).div(toSwap);
uint256 ethForDev = newBalance.mul(tokensForDev).div(toSwap);
uint256 ethForLiquidity = newBalance - (ethForMarketing + ethForDev);
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity);
}
}
uint256 liquidityTokens = contractTokenBalance * tokensForLiquidity / toSwap / 2;
function swapBack() private {
uint256 contractTokenBalance = balanceOf(address(this));
uint256 toSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if (contractTokenBalance > thresholdSwapAmount * 20) {
contractTokenBalance = thresholdSwapAmount * 20;
}
uint256 amountToSwapForETH = contractTokenBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 newBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = newBalance.mul(tokensForMarketing).div(toSwap);
uint256 ethForDev = newBalance.mul(tokensForDev).div(toSwap);
uint256 ethForLiquidity = newBalance - (ethForMarketing + ethForDev);
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity);
}
}
(success,) = address(devWallet).call{ value: (address(this).balance - ethForMarketing) } ("");
(success,) = address(marketingWallet).call{ value: address(this).balance } ("");
} | 9,175,863 | [
1,
13277,
8181,
1267,
2943,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
25793,
538,
12266,
58,
7053,
1766,
39,
94,
38,
330,
715,
2156,
1040,
353,
4232,
39,
3462,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
1071,
11732,
4633,
31,
203,
565,
1758,
1071,
11732,
640,
291,
91,
438,
58,
22,
4154,
31,
203,
203,
203,
565,
1758,
1071,
225,
4461,
16936,
31,
203,
565,
1758,
3238,
13667,
310,
16936,
31,
203,
203,
565,
2254,
5034,
3238,
943,
38,
9835,
6275,
31,
203,
565,
2254,
5034,
3238,
943,
55,
1165,
6275,
31,
27699,
565,
2254,
5034,
3238,
943,
16936,
6275,
31,
203,
7010,
565,
2254,
5034,
3238,
5573,
12521,
6275,
31,
203,
203,
565,
1426,
3238,
353,
1609,
7459,
273,
629,
31,
203,
565,
1426,
1071,
7720,
1526,
273,
629,
31,
203,
565,
1426,
1071,
353,
12521,
1382,
31,
203,
203,
203,
565,
1958,
5782,
281,
288,
203,
3639,
2254,
28,
30143,
5269,
2954,
281,
31,
203,
3639,
2254,
28,
30143,
3882,
21747,
14667,
31,
203,
3639,
2254,
28,
30143,
8870,
14667,
31,
203,
3639,
2254,
28,
30143,
48,
18988,
24237,
14667,
31,
203,
203,
3639,
2254,
28,
357,
80,
5269,
2954,
281,
31,
203,
3639,
2254,
28,
357,
80,
3882,
21747,
14667,
31,
203,
3639,
2254,
28,
357,
80,
8870,
14667,
31,
203,
3639,
2254,
28,
357,
80,
48,
18988,
24237,
14667,
31,
203,
565,
289,
21281,
203,
565,
5782,
281,
1071,
389,
3030,
281,
273,
5782,
281,
12590,
203,
3639,
30143,
5269,
2954,
281,
30,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
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;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IAddressList {
function add(address a) external returns (bool);
function remove(address a) external returns (bool);
function get(address a) external view returns (uint256);
function contains(address a) external view returns (bool);
function length() external view returns (uint256);
function grantRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IAddressListFactory {
function ours(address a) external view returns (bool);
function listCount() external view returns (uint256);
function listAt(uint256 idx) external view returns (address);
function createList() external returns (address listaddr);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
/* solhint-disable func-name-mixedcase */
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
interface ISwapManager {
event OracleCreated(address indexed _sender, address indexed _newOracle, uint256 _period);
function N_DEX() external view returns (uint256);
function ROUTERS(uint256 i) external view returns (IUniswapV2Router02);
function bestOutputFixedInput(
address _from,
address _to,
uint256 _amountIn
)
external
view
returns (
address[] memory path,
uint256 amountOut,
uint256 rIdx
);
function bestPathFixedInput(
address _from,
address _to,
uint256 _amountIn,
uint256 _i
) external view returns (address[] memory path, uint256 amountOut);
function bestInputFixedOutput(
address _from,
address _to,
uint256 _amountOut
)
external
view
returns (
address[] memory path,
uint256 amountIn,
uint256 rIdx
);
function bestPathFixedOutput(
address _from,
address _to,
uint256 _amountOut,
uint256 _i
) external view returns (address[] memory path, uint256 amountIn);
function safeGetAmountsOut(
uint256 _amountIn,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function unsafeGetAmountsOut(
uint256 _amountIn,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function safeGetAmountsIn(
uint256 _amountOut,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function unsafeGetAmountsIn(
uint256 _amountOut,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function comparePathsFixedInput(
address[] memory pathA,
address[] memory pathB,
uint256 _amountIn,
uint256 _i
) external view returns (address[] memory path, uint256 amountOut);
function comparePathsFixedOutput(
address[] memory pathA,
address[] memory pathB,
uint256 _amountOut,
uint256 _i
) external view returns (address[] memory path, uint256 amountIn);
function ours(address a) external view returns (bool);
function oracleCount() external view returns (uint256);
function oracleAt(uint256 idx) external view returns (address);
function getOracle(
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _i
) external view returns (address);
function createOrUpdateOracle(
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _i
) external returns (address oracleAddr);
function consultForFree(
address _from,
address _to,
uint256 _amountIn,
uint256 _period,
uint256 _i
) external view returns (uint256 amountOut, uint256 lastUpdatedAt);
/// get the data we want and pay the gas to update
function consult(
address _from,
address _to,
uint256 _amountIn,
uint256 _period,
uint256 _i
)
external
returns (
uint256 amountOut,
uint256 lastUpdatedAt,
bool updated
);
function updateOracles() external returns (uint256 updated, uint256 expected);
function updateOracles(address[] memory _oracleAddrs) external returns (uint256 updated, uint256 expected);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface CToken {
function accrueInterest() external returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function mint() external payable; // For ETH
function mint(uint256 mintAmount) external returns (uint256); // For ERC20
function redeem(uint256 redeemTokens) external returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function transfer(address user, uint256 amount) external returns (bool);
function transferFrom(
address owner,
address user,
uint256 amount
) external returns (bool);
function balanceOf(address owner) external view returns (uint256);
}
interface Comptroller {
function claimComp(address holder, address[] memory) external;
function compAccrued(address holder) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IStrategy {
function rebalance() external;
function sweepERC20(address _fromToken) external;
function withdraw(uint256 _amount) external;
function feeCollector() external view returns (address);
function isReservedToken(address _token) external view returns (bool);
function migrate(address _newStrategy) external;
function token() external view returns (address);
function totalValue() external view returns (uint256);
function pool() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../bloq/IAddressList.sol";
interface IVesperPool is IERC20 {
function deposit() external payable;
function deposit(uint256 _share) external;
function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool);
function excessDebt(address _strategy) external view returns (uint256);
function permit(
address,
address,
uint256,
uint256,
uint8,
bytes32,
bytes32
) external;
function poolRewards() external returns (address);
function reportEarning(
uint256 _profit,
uint256 _loss,
uint256 _payback
) external;
function reportLoss(uint256 _loss) external;
function resetApproval() external;
function sweepERC20(address _fromToken) external;
function withdraw(uint256 _amount) external;
function withdrawETH(uint256 _amount) external;
function whitelistedWithdraw(uint256 _amount) external;
function governor() external view returns (address);
function keepers() external view returns (IAddressList);
function maintainers() external view returns (IAddressList);
function feeCollector() external view returns (address);
function pricePerShare() external view returns (uint256);
function strategy(address _strategy)
external
view
returns (
bool _active,
uint256 _interestFee,
uint256 _debtRate,
uint256 _lastRebalance,
uint256 _totalDebt,
uint256 _totalLoss,
uint256 _totalProfit,
uint256 _debtRatio
);
function stopEverything() external view returns (bool);
function token() external view returns (IERC20);
function tokensHere() external view returns (uint256);
function totalDebtOf(address _strategy) external view returns (uint256);
function totalValue() external view returns (uint256);
function withdrawFee() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "../interfaces/bloq/ISwapManager.sol";
import "../interfaces/bloq/IAddressList.sol";
import "../interfaces/bloq/IAddressListFactory.sol";
import "../interfaces/vesper/IStrategy.sol";
import "../interfaces/vesper/IVesperPool.sol";
abstract contract Strategy is IStrategy, Context {
using SafeERC20 for IERC20;
IERC20 public immutable collateralToken;
address public receiptToken;
address public immutable override pool;
IAddressList public keepers;
address public override feeCollector;
ISwapManager public swapManager;
uint256 public oraclePeriod = 3600; // 1h
uint256 public oracleRouterIdx = 0; // Uniswap V2
uint256 public swapSlippage = 10000; // 100% Don't use oracles by default
address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
uint256 internal constant MAX_UINT_VALUE = type(uint256).max;
event UpdatedFeeCollector(address indexed previousFeeCollector, address indexed newFeeCollector);
event UpdatedSwapManager(address indexed previousSwapManager, address indexed newSwapManager);
event UpdatedSwapSlippage(uint256 oldSwapSlippage, uint256 newSwapSlippage);
event UpdatedOracleConfig(uint256 oldPeriod, uint256 newPeriod, uint256 oldRouterIdx, uint256 newRouterIdx);
constructor(
address _pool,
address _swapManager,
address _receiptToken
) {
require(_pool != address(0), "pool-address-is-zero");
require(_swapManager != address(0), "sm-address-is-zero");
swapManager = ISwapManager(_swapManager);
pool = _pool;
collateralToken = IVesperPool(_pool).token();
receiptToken = _receiptToken;
}
modifier onlyGovernor {
require(_msgSender() == IVesperPool(pool).governor(), "caller-is-not-the-governor");
_;
}
modifier onlyKeeper() {
require(keepers.contains(_msgSender()), "caller-is-not-a-keeper");
_;
}
modifier onlyPool() {
require(_msgSender() == pool, "caller-is-not-vesper-pool");
_;
}
/**
* @notice Add given address in keepers list.
* @param _keeperAddress keeper address to add.
*/
function addKeeper(address _keeperAddress) external onlyGovernor {
require(keepers.add(_keeperAddress), "add-keeper-failed");
}
/**
* @notice Create keeper list
* NOTE: Any function with onlyKeeper modifier will not work until this function is called.
* NOTE: Due to gas constraint this function cannot be called in constructor.
* @param _addressListFactory To support same code in eth side chain, user _addressListFactory as param
* ethereum- 0xded8217De022706A191eE7Ee0Dc9df1185Fb5dA3
* polygon-0xD10D5696A350D65A9AA15FE8B258caB4ab1bF291
*/
function init(address _addressListFactory) external onlyGovernor {
require(address(keepers) == address(0), "keeper-list-already-created");
// Prepare keeper list
IAddressListFactory _factory = IAddressListFactory(_addressListFactory);
keepers = IAddressList(_factory.createList());
require(keepers.add(_msgSender()), "add-keeper-failed");
}
/**
* @notice Migrate all asset and vault ownership,if any, to new strategy
* @dev _beforeMigration hook can be implemented in child strategy to do extra steps.
* @param _newStrategy Address of new strategy
*/
function migrate(address _newStrategy) external virtual override onlyPool {
require(_newStrategy != address(0), "new-strategy-address-is-zero");
require(IStrategy(_newStrategy).pool() == pool, "not-valid-new-strategy");
_beforeMigration(_newStrategy);
IERC20(receiptToken).safeTransfer(_newStrategy, IERC20(receiptToken).balanceOf(address(this)));
collateralToken.safeTransfer(_newStrategy, collateralToken.balanceOf(address(this)));
}
/**
* @notice Remove given address from keepers list.
* @param _keeperAddress keeper address to remove.
*/
function removeKeeper(address _keeperAddress) external onlyGovernor {
require(keepers.remove(_keeperAddress), "remove-keeper-failed");
}
/**
* @notice Update fee collector
* @param _feeCollector fee collector address
*/
function updateFeeCollector(address _feeCollector) external onlyGovernor {
require(_feeCollector != address(0), "fee-collector-address-is-zero");
require(_feeCollector != feeCollector, "fee-collector-is-same");
emit UpdatedFeeCollector(feeCollector, _feeCollector);
feeCollector = _feeCollector;
}
/**
* @notice Update swap manager address
* @param _swapManager swap manager address
*/
function updateSwapManager(address _swapManager) external onlyGovernor {
require(_swapManager != address(0), "sm-address-is-zero");
require(_swapManager != address(swapManager), "sm-is-same");
emit UpdatedSwapManager(address(swapManager), _swapManager);
swapManager = ISwapManager(_swapManager);
}
function updateSwapSlippage(uint256 _newSwapSlippage) external onlyGovernor {
require(_newSwapSlippage <= 10000, "invalid-slippage-value");
emit UpdatedSwapSlippage(swapSlippage, _newSwapSlippage);
swapSlippage = _newSwapSlippage;
}
function updateOracleConfig(uint256 _newPeriod, uint256 _newRouterIdx) external onlyGovernor {
require(_newRouterIdx < swapManager.N_DEX(), "invalid-router-index");
if (_newPeriod == 0) _newPeriod = oraclePeriod;
require(_newPeriod > 59, "invalid-oracle-period");
emit UpdatedOracleConfig(oraclePeriod, _newPeriod, oracleRouterIdx, _newRouterIdx);
oraclePeriod = _newPeriod;
oracleRouterIdx = _newRouterIdx;
}
/// @dev Approve all required tokens
function approveToken() external onlyKeeper {
_approveToken(0);
_approveToken(MAX_UINT_VALUE);
}
function setupOracles() external onlyKeeper {
_setupOracles();
}
/**
* @dev Withdraw collateral token from lending pool.
* @param _amount Amount of collateral token
*/
function withdraw(uint256 _amount) external override onlyPool {
_withdraw(_amount);
}
/**
* @dev Rebalance profit, loss and investment of this strategy
*/
function rebalance() external virtual override onlyKeeper {
(uint256 _profit, uint256 _loss, uint256 _payback) = _generateReport();
IVesperPool(pool).reportEarning(_profit, _loss, _payback);
_reinvest();
}
/**
* @dev sweep given token to feeCollector of strategy
* @param _fromToken token address to sweep
*/
function sweepERC20(address _fromToken) external override onlyKeeper {
require(feeCollector != address(0), "fee-collector-not-set");
require(_fromToken != address(collateralToken), "not-allowed-to-sweep-collateral");
require(!isReservedToken(_fromToken), "not-allowed-to-sweep");
if (_fromToken == ETH) {
Address.sendValue(payable(feeCollector), address(this).balance);
} else {
uint256 _amount = IERC20(_fromToken).balanceOf(address(this));
IERC20(_fromToken).safeTransfer(feeCollector, _amount);
}
}
/// @notice Returns address of token correspond to collateral token
function token() external view override returns (address) {
return receiptToken;
}
/// @dev Convert from 18 decimals to token defined decimals. Default no conversion.
function convertFrom18(uint256 amount) public pure virtual returns (uint256) {
return amount;
}
/**
* @notice Calculate total value of asset under management
* @dev Report total value in collateral token
*/
function totalValue() external view virtual override returns (uint256 _value);
/// @notice Check whether given token is reserved or not. Reserved tokens are not allowed to sweep.
function isReservedToken(address _token) public view virtual override returns (bool);
/**
* @notice some strategy may want to prepare before doing migration.
Example In Maker old strategy want to give vault ownership to new strategy
* @param _newStrategy .
*/
function _beforeMigration(address _newStrategy) internal virtual;
/**
* @notice Generate report for current profit and loss. Also liquidate asset to payback
* excess debt, if any.
* @return _profit Calculate any realized profit and convert it to collateral, if not already.
* @return _loss Calculate any loss that strategy has made on investment. Convert into collateral token.
* @return _payback If strategy has any excess debt, we have to liquidate asset to payback excess debt.
*/
function _generateReport()
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _payback
)
{
uint256 _excessDebt = IVesperPool(pool).excessDebt(address(this));
uint256 _totalDebt = IVesperPool(pool).totalDebtOf(address(this));
_profit = _realizeProfit(_totalDebt);
_loss = _realizeLoss(_totalDebt);
_payback = _liquidate(_excessDebt);
}
function _calcAmtOutAfterSlippage(uint256 _amount, uint256 _slippage) internal pure returns (uint256) {
return (_amount * (10000 - _slippage)) / (10000);
}
function _simpleOraclePath(address _from, address _to) internal pure returns (address[] memory path) {
if (_from == WETH || _to == WETH) {
path = new address[](2);
path[0] = _from;
path[1] = _to;
} else {
path = new address[](3);
path[0] = _from;
path[1] = WETH;
path[2] = _to;
}
}
function _consultOracle(
address _from,
address _to,
uint256 _amt
) internal returns (uint256, bool) {
// from, to, amountIn, period, router
(uint256 rate, uint256 lastUpdate, ) = swapManager.consult(_from, _to, _amt, oraclePeriod, oracleRouterIdx);
// We're looking at a TWAP ORACLE with a 1 hr Period that has been updated within the last hour
if ((lastUpdate > (block.timestamp - oraclePeriod)) && (rate != 0)) return (rate, true);
return (0, false);
}
function _getOracleRate(address[] memory path, uint256 _amountIn) internal returns (uint256 amountOut) {
require(path.length > 1, "invalid-oracle-path");
amountOut = _amountIn;
bool isValid;
for (uint256 i = 0; i < path.length - 1; i++) {
(amountOut, isValid) = _consultOracle(path[i], path[i + 1], amountOut);
require(isValid, "invalid-oracle-rate");
}
}
/**
* @notice Safe swap via Uniswap / Sushiswap (better rate of the two)
* @dev There are many scenarios when token swap via Uniswap can fail, so this
* method will wrap Uniswap call in a 'try catch' to make it fail safe.
* however, this method will throw minAmountOut is not met
* @param _from address of from token
* @param _to address of to token
* @param _amountIn Amount to be swapped
* @param _minAmountOut minimum amount out
*/
function _safeSwap(
address _from,
address _to,
uint256 _amountIn,
uint256 _minAmountOut
) internal {
(address[] memory path, uint256 amountOut, uint256 rIdx) =
swapManager.bestOutputFixedInput(_from, _to, _amountIn);
if (_minAmountOut == 0) _minAmountOut = 1;
if (amountOut != 0) {
swapManager.ROUTERS(rIdx).swapExactTokensForTokens(
_amountIn,
_minAmountOut,
path,
address(this),
block.timestamp
);
}
}
// These methods can be implemented by the inheriting strategy.
/* solhint-disable no-empty-blocks */
function _claimRewardsAndConvertTo(address _toToken) internal virtual {}
/**
* @notice Set up any oracles that are needed for this strategy.
*/
function _setupOracles() internal virtual {}
/* solhint-enable */
// These methods must be implemented by the inheriting strategy
function _withdraw(uint256 _amount) internal virtual;
function _approveToken(uint256 _amount) internal virtual;
/**
* @notice Withdraw collateral to payback excess debt in pool.
* @param _excessDebt Excess debt of strategy in collateral token
* @return _payback amount in collateral token. Usually it is equal to excess debt.
*/
function _liquidate(uint256 _excessDebt) internal virtual returns (uint256 _payback);
/**
* @notice Calculate earning and withdraw/convert it into collateral token.
* @param _totalDebt Total collateral debt of this strategy
* @return _profit Profit in collateral token
*/
function _realizeProfit(uint256 _totalDebt) internal virtual returns (uint256 _profit);
/**
* @notice Calculate loss
* @param _totalDebt Total collateral debt of this strategy
* @return _loss Realized loss in collateral token
*/
function _realizeLoss(uint256 _totalDebt) internal virtual returns (uint256 _loss);
/**
* @notice Reinvest collateral.
* @dev Once we file report back in pool, we might have some collateral in hand
* which we want to reinvest aka deposit in lender/provider.
*/
function _reinvest() internal virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "../Strategy.sol";
import "../../interfaces/compound/ICompound.sol";
/// @title This strategy will deposit collateral token in Compound and earn interest.
abstract contract CompoundStrategy is Strategy {
using SafeERC20 for IERC20;
CToken internal cToken;
address internal constant COMP = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
Comptroller internal constant COMPTROLLER = Comptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
constructor(
address _pool,
address _swapManager,
address _receiptToken
) Strategy(_pool, _swapManager, _receiptToken) {
require(_receiptToken != address(0), "cToken-address-is-zero");
cToken = CToken(_receiptToken);
swapSlippage = 10000; // disable oracles on reward swaps by default
}
/**
* @notice Calculate total value using COMP accrued and cToken
* @dev Report total value in collateral token
*/
function totalValue() external view virtual override returns (uint256 _totalValue) {
uint256 _compAccrued = COMPTROLLER.compAccrued(address(this));
if (_compAccrued != 0) {
(, _totalValue) = swapManager.bestPathFixedInput(COMP, address(collateralToken), _compAccrued, 0);
}
_totalValue += _convertToCollateral(cToken.balanceOf(address(this)));
}
function isReservedToken(address _token) public view virtual override returns (bool) {
return _token == address(cToken) || _token == COMP;
}
/// @notice Approve all required tokens
function _approveToken(uint256 _amount) internal virtual override {
collateralToken.safeApprove(pool, _amount);
collateralToken.safeApprove(address(cToken), _amount);
for (uint256 i = 0; i < swapManager.N_DEX(); i++) {
IERC20(COMP).safeApprove(address(swapManager.ROUTERS(i)), _amount);
}
}
/**
* @notice Claim COMP and transfer to new strategy
* @param _newStrategy Address of new strategy.
*/
function _beforeMigration(address _newStrategy) internal virtual override {
_claimComp();
IERC20(COMP).safeTransfer(_newStrategy, IERC20(COMP).balanceOf(address(this)));
}
/// @notice Claim comp
function _claimComp() internal {
address[] memory _markets = new address[](1);
_markets[0] = address(cToken);
COMPTROLLER.claimComp(address(this), _markets);
}
/// @notice Claim COMP and convert COMP into collateral token.
function _claimRewardsAndConvertTo(address _toToken) internal override {
_claimComp();
uint256 _compAmount = IERC20(COMP).balanceOf(address(this));
if (_compAmount != 0) {
uint256 minAmtOut =
(swapSlippage != 10000)
? _calcAmtOutAfterSlippage(
_getOracleRate(_simpleOraclePath(COMP, _toToken), _compAmount),
swapSlippage
)
: 1;
_safeSwap(COMP, _toToken, _compAmount, minAmtOut);
}
}
/// @notice Withdraw collateral to payback excess debt
function _liquidate(uint256 _excessDebt) internal override returns (uint256 _payback) {
if (_excessDebt != 0) {
_payback = _safeWithdraw(_excessDebt);
}
}
/**
* @notice Calculate earning and withdraw it from Compound.
* @dev Claim COMP and convert into collateral
* @dev If somehow we got some collateral token in strategy then we want to
* include those in profit. That's why we used 'return' outside 'if' condition.
* @param _totalDebt Total collateral debt of this strategy
* @return profit in collateral token
*/
function _realizeProfit(uint256 _totalDebt) internal virtual override returns (uint256) {
_claimRewardsAndConvertTo(address(collateralToken));
uint256 _collateralBalance = _convertToCollateral(cToken.balanceOf(address(this)));
if (_collateralBalance > _totalDebt) {
_withdrawHere(_collateralBalance - _totalDebt);
}
return collateralToken.balanceOf(address(this));
}
/**
* @notice Calculate realized loss.
* @return _loss Realized loss in collateral token
*/
function _realizeLoss(uint256 _totalDebt) internal view override returns (uint256 _loss) {
uint256 _collateralBalance = _convertToCollateral(cToken.balanceOf(address(this)));
if (_collateralBalance < _totalDebt) {
_loss = _totalDebt - _collateralBalance;
}
}
/// @notice Deposit collateral in Compound
function _reinvest() internal virtual override {
uint256 _collateralBalance = collateralToken.balanceOf(address(this));
if (_collateralBalance != 0) {
require(cToken.mint(_collateralBalance) == 0, "deposit-to-compound-failed");
}
}
/// @dev Withdraw collateral and transfer it to pool
function _withdraw(uint256 _amount) internal override {
_safeWithdraw(_amount);
collateralToken.safeTransfer(pool, collateralToken.balanceOf(address(this)));
}
/**
* @notice Safe withdraw will make sure to check asking amount against available amount.
* @param _amount Amount of collateral to withdraw.
* @return Actual collateral withdrawn
*/
function _safeWithdraw(uint256 _amount) internal returns (uint256) {
uint256 _collateralBalance = _convertToCollateral(cToken.balanceOf(address(this)));
// Get minimum of _amount and _collateralBalance
return _withdrawHere(_amount < _collateralBalance ? _amount : _collateralBalance);
}
/// @dev Withdraw collateral here. Do not transfer to pool
function _withdrawHere(uint256 _amount) internal returns (uint256) {
if (_amount != 0) {
require(cToken.redeemUnderlying(_amount) == 0, "withdraw-from-compound-failed");
_afterRedeem();
}
return _amount;
}
function _setupOracles() internal override {
swapManager.createOrUpdateOracle(COMP, WETH, oraclePeriod, oracleRouterIdx);
if (address(collateralToken) != WETH) {
swapManager.createOrUpdateOracle(WETH, address(collateralToken), oraclePeriod, oracleRouterIdx);
}
}
/**
* @dev Compound support ETH as collateral not WETH. This hook will take
* care of conversion from WETH to ETH and vice versa.
* @dev This will be used in ETH strategy only, hence empty implementation
*/
//solhint-disable-next-line no-empty-blocks
function _afterRedeem() internal virtual {}
function _convertToCollateral(uint256 _cTokenAmount) internal view returns (uint256) {
return (_cTokenAmount * cToken.exchangeRateStored()) / 1e18;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "../compound/CompoundStrategy.sol";
/// @title This strategy will deposit collateral token in C.R.E.A.M. and earn interest.
abstract contract CreamStrategy is CompoundStrategy {
using SafeERC20 for IERC20;
// solhint-disable no-empty-blocks
constructor(
address _pool,
address _swapManager,
address _receiptToken
) CompoundStrategy(_pool, _swapManager, _receiptToken) {}
// solhint-enable no-empty-blocks
/**
* @notice Calculate total value using underlying token
* @dev Report total value in collateral token
*/
function totalValue() external view override returns (uint256 _totalValue) {
_totalValue = _convertToCollateral(cToken.balanceOf(address(this)));
}
function isReservedToken(address _token) public view override returns (bool) {
return _token == address(cToken);
}
/// @notice Approve all required tokens
function _approveToken(uint256 _amount) internal override {
collateralToken.safeApprove(pool, _amount);
collateralToken.safeApprove(address(cToken), _amount);
}
// solhint-disable-next-line
function _beforeMigration(address _newStrategy) internal override {}
/**
* @notice Calculate earning and withdraw it from C.R.E.A.M.
* @dev If somehow we got some collateral token in strategy then we want to
* include those in profit. That's why we used 'return' outside 'if' condition.
* Since there aren't token rewards here, we call accrueInterst
* to make sure we get the maximum accrued interest on rebalance
* @param _totalDebt Total collateral debt of this strategy
* @return profit in collateral token
*/
function _realizeProfit(uint256 _totalDebt) internal override returns (uint256) {
cToken.accrueInterest();
uint256 _collateralBalance = _convertToCollateral(cToken.balanceOf(address(this)));
if (_collateralBalance > _totalDebt) {
_withdrawHere(_collateralBalance - _totalDebt);
}
return collateralToken.balanceOf(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./CreamStrategy.sol";
// solhint-disable no-empty-blocks
/// @title Deposit USDT in C.R.E.A.M. and earn interest.
contract CreamStrategyUSDT is CreamStrategy {
string public constant NAME = "Cream-Strategy-USDT";
string public constant VERSION = "3.0.11";
// crUSDT = 0x797AAB1ce7c01eB727ab980762bA88e7133d2157
constructor(address _pool, address _swapManager)
CreamStrategy(_pool, _swapManager, 0x797AAB1ce7c01eB727ab980762bA88e7133d2157)
{}
}
| solhint-disable no-empty-blocks @title Deposit USDT in C.R.E.A.M. and earn interest. crUSDT = 0x797AAB1ce7c01eB727ab980762bA88e7133d2157 | contract CreamStrategyUSDT is CreamStrategy {
string public constant NAME = "Cream-Strategy-USDT";
string public constant VERSION = "3.0.11";
constructor(address _pool, address _swapManager)
CreamStrategy(_pool, _swapManager, 0x797AAB1ce7c01eB727ab980762bA88e7133d2157)
{}
}
| 13,668,858 | [
1,
18281,
11317,
17,
8394,
1158,
17,
5531,
17,
7996,
225,
4019,
538,
305,
11836,
9081,
316,
385,
18,
54,
18,
41,
18,
37,
18,
49,
18,
471,
425,
1303,
16513,
18,
4422,
3378,
9081,
273,
374,
92,
7235,
27,
37,
2090,
21,
311,
27,
71,
1611,
73,
38,
27,
5324,
378,
29,
3672,
6669,
22,
70,
37,
5482,
73,
27,
28615,
72,
22,
27985,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
385,
793,
4525,
3378,
9081,
353,
385,
793,
4525,
288,
203,
565,
533,
1071,
5381,
6048,
273,
315,
39,
793,
17,
4525,
17,
3378,
9081,
14432,
203,
565,
533,
1071,
5381,
8456,
273,
315,
23,
18,
20,
18,
2499,
14432,
203,
203,
565,
3885,
12,
2867,
389,
6011,
16,
1758,
389,
22270,
1318,
13,
203,
3639,
385,
793,
4525,
24899,
6011,
16,
389,
22270,
1318,
16,
374,
92,
7235,
27,
37,
2090,
21,
311,
27,
71,
1611,
73,
38,
27,
5324,
378,
29,
3672,
6669,
22,
70,
37,
5482,
73,
27,
28615,
72,
22,
27985,
13,
203,
203,
565,
2618,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.25;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
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);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
// Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @dev Library to perform safe calls to standard method for ERC20 tokens.
*
* Why Transfers: transfer methods could have a return value (bool), throw or revert for insufficient funds or
* unathorized value.
*
* Why Approve: approve method could has a return value (bool) or does not accept 0 as a valid value (BNB token).
* The common strategy used to clean approvals.
*
* We use the Solidity call instead of interface methods because in the case of transfer, it will fail
* for tokens with an implementation without returning a value.
* Since versions of Solidity 0.4.22 the EVM has a new opcode, called RETURNDATASIZE.
* This opcode stores the size of the returned data of an external call. The code checks the size of the return value
* after an external call and reverts the transaction in case the return data is shorter than expected
*/
library SafeERC20 {
using SafeMath for uint256;
/**
* @dev Transfer token for a specified address
* @param _token erc20 The address of the ERC20 contract
* @param _to address The address which you want to transfer to
* @param _value uint256 the _value of tokens to be transferred
* @return bool whether the transfer was successful or not
*/
function safeTransfer(IERC20 _token, address _to, uint256 _value) internal returns (bool) {
uint256 prevBalance = _token.balanceOf(address(this));
if (prevBalance < _value) {
// Insufficient funds
return false;
}
address(_token).call(
abi.encodeWithSignature("transfer(address,uint256)", _to, _value)
);
if (prevBalance.sub(_value) != _token.balanceOf(address(this))) {
// Transfer failed
return false;
}
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _token erc20 The address of the ERC20 contract
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the _value of tokens to be transferred
* @return bool whether the transfer was successful or not
*/
function safeTransferFrom(
IERC20 _token,
address _from,
address _to,
uint256 _value
) internal returns (bool)
{
uint256 prevBalance = _token.balanceOf(_from);
if (prevBalance < _value) {
// Insufficient funds
return false;
}
if (_token.allowance(_from, address(this)) < _value) {
// Insufficient allowance
return false;
}
address(_token).call(
abi.encodeWithSignature("transferFrom(address,address,uint256)", _from, _to, _value)
);
if (prevBalance.sub(_value) != _token.balanceOf(_from)) {
// Transfer failed
return false;
}
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* @param _token erc20 The address of the ERC20 contract
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
* @return bool whether the approve was successful or not
*/
function safeApprove(IERC20 _token, address _spender, uint256 _value) internal returns (bool) {
address(_token).call(
abi.encodeWithSignature("approve(address,uint256)", _spender, _value)
);
if (_token.allowance(address(this), _spender) != _value) {
// Approve failed
return false;
}
return true;
}
}
/**
* @title SEEDDEX
* @dev This is the main contract for the SEEDDEX exchange.
*/
contract SEEDDEX {
using SafeERC20 for IERC20;
/// Variables
address public admin; // the admin address
address constant public FicAddress = 0x0DD83B5013b2ad7094b1A7783d96ae0168f82621; // FloraFIC token address
address public manager; // the manager address
address public feeAccount; // the account that will receive fees
uint public feeTakeMaker; // For Maker fee x% *10^18
uint public feeTakeSender; // For Sender fee x% *10^18
uint public feeTakeMakerFic;
uint public feeTakeSenderFic;
bool private depositingTokenFlag; // True when Token.safeTransferFrom is being called from depositToken
mapping(address => mapping(address => uint)) public tokens; // mapping of token addresses to mapping of account balances (token=0 means Ether)
mapping(address => mapping(bytes32 => bool)) public orders; // mapping of user accounts to mapping of order hashes to booleans (true = submitted by user, equivalent to offchain signature)
mapping(address => mapping(bytes32 => uint)) public orderFills; // mapping of user accounts to mapping of order hashes to uints (amount of order that has been filled)
address public predecessor; // Address of the previous version of this contract. If address(0), this is the first version
address public successor; // Address of the next version of this contract. If address(0), this is the most up to date version.
uint16 public version; // This is the version # of the contract
/// Logging Events
event Order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address indexed user, bytes32 hash, uint amount);
event Cancel(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address indexed user, uint8 v, bytes32 r, bytes32 s);
event Trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address get, address give, uint256 timestamp);
event Deposit(address token, address indexed user, uint amount, uint balance);
event Withdraw(address token, address indexed user, uint amount, uint balance);
event FundsMigrated(address indexed user, address newContract);
/// This is a modifier for functions to check if the sending user address is the same as the admin user address.
modifier isAdmin() {
require(msg.sender == admin);
_;
}
/// this is manager can only change feeTakeMaker feeTakeMaker and change manager address (accept only Ethereum address)
modifier isManager() {
require(msg.sender == manager || msg.sender == admin);
_;
}
/// Constructor function. This is only called on contract creation.
function SEEDDEX(address admin_, address manager_, address feeAccount_, uint feeTakeMaker_, uint feeTakeSender_, uint feeTakeMakerFic_, uint feeTakeSenderFic_, address predecessor_) public {
admin = admin_;
manager = manager_;
feeAccount = feeAccount_;
feeTakeMaker = feeTakeMaker_;
feeTakeSender = feeTakeSender_;
feeTakeMakerFic = feeTakeMakerFic_;
feeTakeSenderFic = feeTakeSenderFic_;
depositingTokenFlag = false;
predecessor = predecessor_;
if (predecessor != address(0)) {
version = SEEDDEX(predecessor).version() + 1;
} else {
version = 1;
}
}
/// The fallback function. Ether transfered into the contract is not accepted.
function() public {
revert();
}
/// Changes the official admin user address. Accepts Ethereum address.
function changeAdmin(address admin_) public isAdmin {
require(admin_ != address(0));
admin = admin_;
}
/// Changes the manager user address. Accepts Ethereum address.
function changeManager(address manager_) public isManager {
require(manager_ != address(0));
manager = manager_;
}
/// Changes the account address that receives trading fees. Accepts Ethereum address.
function changeFeeAccount(address feeAccount_) public isAdmin {
feeAccount = feeAccount_;
}
/// Changes the fee on takes. Can only be changed to a value less than it is currently set at.
function changeFeeTakeMaker(uint feeTakeMaker_) public isManager {
feeTakeMaker = feeTakeMaker_;
}
function changeFeeTakeSender(uint feeTakeSender_) public isManager {
feeTakeSender = feeTakeSender_;
}
function changeFeeTakeMakerFic(uint feeTakeMakerFic_) public isManager {
feeTakeMakerFic = feeTakeMakerFic_;
}
function changeFeeTakeSenderFic(uint feeTakeSenderFic_) public isManager {
feeTakeSenderFic = feeTakeSenderFic_;
}
/// Changes the successor. Used in updating the contract.
function setSuccessor(address successor_) public isAdmin {
require(successor_ != address(0));
successor = successor_;
}
////////////////////////////////////////////////////////////////////////////////
// Deposits, Withdrawals, Balances
////////////////////////////////////////////////////////////////////////////////
/**
* This function handles deposits of Ether into the contract.
* Emits a Deposit event.
* Note: With the payable modifier, this function accepts Ether.
*/
function deposit() public payable {
tokens[0][msg.sender] = SafeMath.add(tokens[0][msg.sender], msg.value);
Deposit(0, msg.sender, msg.value, tokens[0][msg.sender]);
}
/**
* This function handles withdrawals of Ether from the contract.
* Verifies that the user has enough funds to cover the withdrawal.
* Emits a Withdraw event.
* @param amount uint of the amount of Ether the user wishes to withdraw
*/
function withdraw(uint amount) {
if (tokens[0][msg.sender] < amount) throw;
tokens[0][msg.sender] = SafeMath.sub(tokens[0][msg.sender], amount);
if (!msg.sender.call.value(amount)()) throw;
Withdraw(0, msg.sender, amount, tokens[0][msg.sender]);
}
/**
* This function handles deposits of Ethereum based tokens to the contract.
* Does not allow Ether.
* If token transfer fails, transaction is reverted and remaining gas is refunded.
* Emits a Deposit event.
* Note: Remember to call IERC20(address).safeApprove(this, amount) or this contract will not be able to do the transfer on your behalf.
* @param token Ethereum contract address of the token or 0 for Ether
* @param amount uint of the amount of the token the user wishes to deposit
*/
function depositToken(address token, uint amount) {
//remember to call IERC20(address).safeApprove(this, amount) or this contract will not be able to do the transfer on your behalf.
if (token == 0) throw;
if (!IERC20(token).safeTransferFrom(msg.sender, this, amount)) throw;
tokens[token][msg.sender] = SafeMath.add(tokens[token][msg.sender], amount);
Deposit(token, msg.sender, amount, tokens[token][msg.sender]);
}
/**
* This function provides a fallback solution as outlined in ERC223.
* If tokens are deposited through depositToken(), the transaction will continue.
* If tokens are sent directly to this contract, the transaction is reverted.
* @param sender Ethereum address of the sender of the token
* @param amount amount of the incoming tokens
* @param data attached data similar to msg.data of Ether transactions
*/
function tokenFallback(address sender, uint amount, bytes data) public returns (bool ok) {
if (depositingTokenFlag) {
// Transfer was initiated from depositToken(). User token balance will be updated there.
return true;
} else {
// Direct ECR223 Token.safeTransfer into this contract not allowed, to keep it consistent
// with direct transfers of ECR20 and ETH.
revert();
}
}
/**
* This function handles withdrawals of Ethereum based tokens from the contract.
* Does not allow Ether.
* If token transfer fails, transaction is reverted and remaining gas is refunded.
* Emits a Withdraw event.
* @param token Ethereum contract address of the token or 0 for Ether
* @param amount uint of the amount of the token the user wishes to withdraw
*/
function withdrawToken(address token, uint amount) {
if (token == 0) throw;
if (tokens[token][msg.sender] < amount) throw;
tokens[token][msg.sender] = SafeMath.sub(tokens[token][msg.sender], amount);
if (!IERC20(token).safeTransfer(msg.sender, amount)) throw;
Withdraw(token, msg.sender, amount, tokens[token][msg.sender]);
}
/**
* Retrieves the balance of a token based on a user address and token address.
* @param token Ethereum contract address of the token or 0 for Ether
* @param user Ethereum address of the user
* @return the amount of tokens on the exchange for a given user address
*/
function balanceOf(address token, address user) public constant returns (uint) {
return tokens[token][user];
}
////////////////////////////////////////////////////////////////////////////////
// Trading
////////////////////////////////////////////////////////////////////////////////
/**
* Stores the active order inside of the contract.
* Emits an Order event.
*
*
* Note: tokenGet & tokenGive can be the Ethereum contract address.
* @param tokenGet Ethereum contract address of the token to receive
* @param amountGet uint amount of tokens being received
* @param tokenGive Ethereum contract address of the token to give
* @param amountGive uint amount of tokens being given
* @param expires uint of block number when this order should expire
* @param nonce arbitrary random number
*/
function order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce) public {
bytes32 hash = keccak256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
uint amount;
orders[msg.sender][hash] = true;
Order(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender, hash, amount);
}
/**
* Facilitates a trade from one user to another.
* Requires that the transaction is signed properly, the trade isn't past its expiration, and all funds are present to fill the trade.
* Calls tradeBalances().
* Updates orderFills with the amount traded.
* Emits a Trade event.
* Note: tokenGet & tokenGive can be the Ethereum contract address.
* Note: amount is in amountGet / tokenGet terms.
* @param tokenGet Ethereum contract address of the token to receive
* @param amountGet uint amount of tokens being received
* @param tokenGive Ethereum contract address of the token to give
* @param amountGive uint amount of tokens being given
* @param expires uint of block number when this order should expire
* @param nonce arbitrary random number
* @param user Ethereum address of the user who placed the order
* @param v part of signature for the order hash as signed by user
* @param r part of signature for the order hash as signed by user
* @param s part of signature for the order hash as signed by user
* @param amount uint amount in terms of tokenGet that will be "buy" in the trade
*/
function trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount) public {
bytes32 hash = keccak256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
require((
(orders[user][hash] || ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s) == user) &&
block.number <= expires &&
SafeMath.add(orderFills[user][hash], amount) <= amountGet
));
tradeBalances(tokenGet, amountGet, tokenGive, amountGive, user, amount);
orderFills[user][hash] = SafeMath.add(orderFills[user][hash], amount);
Trade(tokenGet, amount, tokenGive, amountGive * amount / amountGet, user, msg.sender, now);
}
/**
* This is a private function and is only being called from trade().
* Handles the movement of funds when a trade occurs.
* Takes fees.
* Updates token balances for both buyer and seller.
* Note: tokenGet & tokenGive can be the Ethereum contract address.
* Note: amount is in amountGet / tokenGet terms.
* @param tokenGet Ethereum contract address of the token to receive
* @param amountGet uint amount of tokens being received
* @param tokenGive Ethereum contract address of the token to give
* @param amountGive uint amount of tokens being given
* @param user Ethereum address of the user who placed the order
* @param amount uint amount in terms of tokenGet that will be "buy" in the trade
*/
function tradeBalances(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address user, uint amount) private {
if (tokenGet == FicAddress || tokenGive == FicAddress) {
tokens[tokenGet][msg.sender] = SafeMath.sub(tokens[tokenGet][msg.sender], amount);
tokens[tokenGet][user] = SafeMath.add(tokens[tokenGet][user], SafeMath.mul(amount, ((1 ether) - feeTakeMakerFic)) / (1 ether));
tokens[tokenGet][feeAccount] = SafeMath.add(tokens[tokenGet][feeAccount], SafeMath.mul(amount, feeTakeMakerFic) / (1 ether));
tokens[tokenGive][user] = SafeMath.sub(tokens[tokenGive][user], SafeMath.mul(amountGive, amount) / amountGet);
tokens[tokenGive][msg.sender] = SafeMath.add(tokens[tokenGive][msg.sender], SafeMath.mul(SafeMath.mul(((1 ether) - feeTakeSenderFic), amountGive), amount) / amountGet / (1 ether));
tokens[tokenGive][feeAccount] = SafeMath.add(tokens[tokenGive][feeAccount], SafeMath.mul(SafeMath.mul(feeTakeSenderFic, amountGive), amount) / amountGet / (1 ether));
}
else {
tokens[tokenGet][msg.sender] = SafeMath.sub(tokens[tokenGet][msg.sender], amount);
tokens[tokenGet][user] = SafeMath.add(tokens[tokenGet][user], SafeMath.mul(amount, ((1 ether) - feeTakeMaker)) / (1 ether));
tokens[tokenGet][feeAccount] = SafeMath.add(tokens[tokenGet][feeAccount], SafeMath.mul(amount, feeTakeMaker) / (1 ether));
tokens[tokenGive][user] = SafeMath.sub(tokens[tokenGive][user], SafeMath.mul(amountGive, amount) / amountGet);
tokens[tokenGive][msg.sender] = SafeMath.add(tokens[tokenGive][msg.sender], SafeMath.mul(SafeMath.mul(((1 ether) - feeTakeSender), amountGive), amount) / amountGet / (1 ether));
tokens[tokenGive][feeAccount] = SafeMath.add(tokens[tokenGive][feeAccount], SafeMath.mul(SafeMath.mul(feeTakeSender, amountGive), amount) / amountGet / (1 ether));
}
}
/**
* This function is to test if a trade would go through.
* Note: tokenGet & tokenGive can be the Ethereum contract address.
* Note: amount is in amountGet / tokenGet terms.
* @param tokenGet Ethereum contract address of the token to receive
* @param amountGet uint amount of tokens being received
* @param tokenGive Ethereum contract address of the token to give
* @param amountGive uint amount of tokens being given
* @param expires uint of block number when this order should expire
* @param nonce arbitrary random number
* @param user Ethereum address of the user who placed the order
* @param v part of signature for the order hash as signed by user
* @param r part of signature for the order hash as signed by user
* @param s part of signature for the order hash as signed by user
* @param amount uint amount in terms of tokenGet that will be "buy" in the trade
* @param sender Ethereum address of the user taking the order
* @return bool: true if the trade would be successful, false otherwise
*/
function testTrade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount, address sender) public constant returns (bool) {
if (!(
tokens[tokenGet][sender] >= amount &&
availableVolume(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, user, v, r, s) >= amount
)) {
return false;
} else {
return true;
}
}
/**
* This function checks the available volume for a given order.
* Note: tokenGet & tokenGive can be the Ethereum contract address.
* @param tokenGet Ethereum contract address of the token to receive
* @param amountGet uint amount of tokens being received
* @param tokenGive Ethereum contract address of the token to give
* @param amountGive uint amount of tokens being given
* @param expires uint of block number when this order should expire
* @param nonce arbitrary random number
* @param user Ethereum address of the user who placed the order
* @param v part of signature for the order hash as signed by user
* @param r part of signature for the order hash as signed by user
* @param s part of signature for the order hash as signed by user
* @return uint: amount of volume available for the given order in terms of amountGet / tokenGet
*/
function availableVolume(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) public constant returns (uint) {
bytes32 hash = keccak256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
if (!(
(orders[user][hash] || ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s) == user) &&
block.number <= expires
)) {
return 0;
}
uint[2] memory available;
available[0] = SafeMath.sub(amountGet, orderFills[user][hash]);
available[1] = SafeMath.mul(tokens[tokenGive][user], amountGet) / amountGive;
if (available[0] < available[1]) {
return available[0];
} else {
return available[1];
}
}
/**
* This function checks the amount of an order that has already been filled.
* Note: tokenGet & tokenGive can be the Ethereum contract address.
* @param tokenGet Ethereum contract address of the token to receive
* @param amountGet uint amount of tokens being received
* @param tokenGive Ethereum contract address of the token to give
* @param amountGive uint amount of tokens being given
* @param expires uint of block number when this order should expire
* @param nonce arbitrary random number
* @param user Ethereum address of the user who placed the order
* @param v part of signature for the order hash as signed by user
* @param r part of signature for the order hash as signed by user
* @param s part of signature for the order hash as signed by user
* @return uint: amount of the given order that has already been filled in terms of amountGet / tokenGet
*/
function amountFilled(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) public constant returns (uint) {
bytes32 hash = keccak256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
return orderFills[user][hash];
}
/**
* This function cancels a given order by editing its fill data to the full amount.
* Requires that the transaction is signed properly.
* Updates orderFills to the full amountGet
* Emits a Cancel event.
* Note: tokenGet & tokenGive can be the Ethereum contract address.
* @param tokenGet Ethereum contract address of the token to receive
* @param amountGet uint amount of tokens being received
* @param tokenGive Ethereum contract address of the token to give
* @param amountGive uint amount of tokens being given
* @param expires uint of block number when this order should expire
* @param nonce arbitrary random number
* @param v part of signature for the order hash as signed by user
* @param r part of signature for the order hash as signed by user
* @param s part of signature for the order hash as signed by user
* @return uint: amount of the given order that has already been filled in terms of amountGet / tokenGet
*/
function cancelOrder(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, uint8 v, bytes32 r, bytes32 s) public {
bytes32 hash = keccak256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
require((orders[msg.sender][hash] || ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s) == msg.sender));
orderFills[msg.sender][hash] = amountGet;
Cancel(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender, v, r, s);
}
////////////////////////////////////////////////////////////////////////////////
// Contract Versioning / Migration
////////////////////////////////////////////////////////////////////////////////
/**
* User triggered function to migrate funds into a new contract to ease updates.
* Emits a FundsMigrated event.
* @param newContract Contract address of the new contract we are migrating funds to
* @param tokens_ Array of token addresses that we will be migrating to the new contract
*/
function migrateFunds(address newContract, address[] tokens_) public {
require(newContract != address(0));
SEEDDEX newExchange = SEEDDEX(newContract);
// Move Ether into new exchange.
uint etherAmount = tokens[0][msg.sender];
if (etherAmount > 0) {
tokens[0][msg.sender] = 0;
newExchange.depositForUser.value(etherAmount)(msg.sender);
}
// Move Tokens into new exchange.
for (uint16 n = 0; n < tokens_.length; n++) {
address token = tokens_[n];
require(token != address(0));
// Ether is handled above.
uint tokenAmount = tokens[token][msg.sender];
if (tokenAmount != 0) {
if (!IERC20(token).safeApprove(newExchange, tokenAmount)) throw;
tokens[token][msg.sender] = 0;
newExchange.depositTokenForUser(token, tokenAmount, msg.sender);
}
}
FundsMigrated(msg.sender, newContract);
}
/**
* This function handles deposits of Ether into the contract, but allows specification of a user.
* Note: This is generally used in migration of funds.
* Note: With the payable modifier, this function accepts Ether.
*/
function depositForUser(address user) public payable {
require(user != address(0));
require(msg.value > 0);
tokens[0][user] = SafeMath.add(tokens[0][user], (msg.value));
}
/**
* This function handles deposits of Ethereum based tokens into the contract, but allows specification of a user.
* Does not allow Ether.
* If token transfer fails, transaction is reverted and remaining gas is refunded.
* Note: This is generally used in migration of funds.
* Note: Remember to call Token(address).safeApprove(this, amount) or this contract will not be able to do the transfer on your behalf.
* @param token Ethereum contract address of the token
* @param amount uint of the amount of the token the user wishes to deposit
*/
function depositTokenForUser(address token, uint amount, address user) public {
require(token != address(0));
require(user != address(0));
require(amount > 0);
depositingTokenFlag = true;
if (!IERC20(token).safeTransferFrom(msg.sender, this, amount)) throw;
depositingTokenFlag = false;
tokens[token][user] = SafeMath.add(tokens[token][user], (amount));
}
} | * This function provides a fallback solution as outlined in ERC223. If tokens are deposited through depositToken(), the transaction will continue. If tokens are sent directly to this contract, the transaction is reverted. @param sender Ethereum address of the sender of the token @param amount amount of the incoming tokens @param data attached data similar to msg.data of Ether transactions/ Transfer was initiated from depositToken(). User token balance will be updated there. Direct ECR223 Token.safeTransfer into this contract not allowed, to keep it consistent with direct transfers of ECR20 and ETH. | function tokenFallback(address sender, uint amount, bytes data) public returns (bool ok) {
if (depositingTokenFlag) {
return true;
revert();
}
}
| 13,035,700 | [
1,
2503,
445,
8121,
279,
5922,
6959,
487,
596,
22316,
316,
4232,
39,
3787,
23,
18,
971,
2430,
854,
443,
1724,
329,
3059,
443,
1724,
1345,
9334,
326,
2492,
903,
1324,
18,
971,
2430,
854,
3271,
5122,
358,
333,
6835,
16,
326,
2492,
353,
15226,
329,
18,
225,
5793,
512,
18664,
379,
1758,
434,
326,
5793,
434,
326,
1147,
225,
3844,
3844,
434,
326,
6935,
2430,
225,
501,
7495,
501,
7281,
358,
1234,
18,
892,
434,
512,
1136,
8938,
19,
12279,
1703,
27183,
628,
443,
1724,
1345,
7675,
2177,
1147,
11013,
903,
506,
3526,
1915,
18,
9908,
512,
5093,
3787,
23,
3155,
18,
4626,
5912,
1368,
333,
6835,
486,
2935,
16,
358,
3455,
518,
11071,
598,
2657,
29375,
434,
512,
5093,
3462,
471,
512,
2455,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1147,
12355,
12,
2867,
5793,
16,
2254,
3844,
16,
1731,
501,
13,
1071,
1135,
261,
6430,
1529,
13,
288,
203,
3639,
309,
261,
323,
1724,
310,
1345,
4678,
13,
288,
203,
5411,
327,
638,
31,
203,
5411,
15226,
5621,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2020-10-15
*/
pragma solidity 0.5.15;
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
contract Owner {
address public OwnerAddress;
modifier isOwner(){
require( msg.sender == OwnerAddress);
_;
}
function changeOwner ( address _newAddress )
isOwner
public
returns ( bool )
{
OwnerAddress = _newAddress;
return true;
}
}
contract ERC20 {
using SafeMath for uint256;
string public name;
string public symbol;
string public desc;
uint8 public decimals;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _allowances;
uint256 _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 `TokenOwner` is set by
* a call to `approve`. `value` is the new allowance.
*/
event Approval(address indexed TokenOwner, address indexed spender, uint256 value);
/**
* @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(msg.sender, recipient, amount);
return true;
}
/**
* @dev See `IERC20.allowance`.
*/
function allowance(address TokenOwner, address spender) public view returns (uint256) {
return _allowances[TokenOwner][spender];
}
/**
* @dev See `IERC20.approve`.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
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 `value`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
require(_allowances[sender][msg.sender] >= amount, "ERC20: Not enough in deligation");
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* 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(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to `transfer`, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a `Transfer` event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(_balances[sender] >= amount, "ERC20: Not Enough balance");
_balances[sender] = _balances[sender].sub(amount);
_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 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `TokenOwner`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:
*
* - `TokenOwner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address TokenOwner, address spender, uint256 value) internal {
require(TokenOwner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[TokenOwner][spender] = value;
emit Approval(TokenOwner, spender, value);
}
/**
* @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, msg.sender, _allowances[account][msg.sender].sub(amount));
}
}
contract IBTCToken is ERC20 , Owner{
address public TAddr;
modifier isTreasury(){
require(msg.sender == TAddr);
_;
}
constructor( )
public
{
name = "IBTC Blockchain";
symbol = "IBTC";
desc = "IBTC Blockchain";
decimals = 18;
OwnerAddress = msg.sender;
}
function setTreasury ( address _TAddres)
isOwner
public
returns ( bool )
{
TAddr = _TAddres;
return true;
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function mint(address recipient, uint256 amount)
isTreasury
public
returns (bool result )
{
_mint( recipient , amount );
result = true;
}
function transfer(address recipient, uint256 amount)
public
returns (bool result )
{
_transfer(msg.sender, recipient , amount );
result = true;
}
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
require(_allowances[sender][msg.sender] >= amount, "ERC20: Not enough in deligation");
_transfer(msg.sender, recipient , amount );
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
function allowance(address TokenOwner, address spender) public view returns (uint256) {
return _allowances[TokenOwner][spender];
}
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
}
contract Treasury_ds is Owner {
using SafeMath for uint256;
bool public contractState;
IBTCToken Token;
address public TokenAddr;
address payable public Owner1;
address payable public Owner2;
address masterAddr;
uint256 public Rate;
bool public enabled;
mapping ( uint256 => LLimit ) public Levels;
struct LLimit{
uint256 percent;
uint256 salesLimit;
uint256 bonus;
}
uint256 public MaxLevel;
// Child -> Parent Mapping
mapping ( address => address ) public PCTree;
mapping ( address => userData ) public userLevel;
struct userData{
uint256 level;
uint256 sales;
uint256 share;
uint256 bonus;
}
modifier isInActive(){
require(contractState == false);
_;
}
modifier isActive(){
require(contractState == true);
_;
}
modifier isSameLength ( uint256 _s1 , uint256 _s2 ){
require(_s1 == _s2);
_;
}
modifier isVaildClaim( uint256 _amt ){
require( userLevel[msg.sender].share >= _amt );
_;
}
modifier isVaildReferer( address _ref ){
require( userLevel[_ref].level != 0 );
_;
}
modifier isSaleClose ( uint256 _amt ){
require( enabled == true );
_;
}
modifier isValidTOwner(){
require(( Owner1 == msg.sender ) || (Owner2 == msg.sender));
_;
}
event puchaseEvent( address indexed _buyer , address indexed _referer , uint256 _value , uint256 _tokens );
event claimEvent( address indexed _buyer , uint256 _value , uint256 _pendingShare );
}
contract Treasury is Treasury_ds{
constructor( address _TAddr )
public
{
Token = IBTCToken( _TAddr );
TokenAddr = _TAddr;
OwnerAddress = msg.sender;
contractState = false;
}
function setLevels( uint256[] memory _percent , uint256[] memory _salesLimit , uint256[] memory _bonus )
isSameLength( _salesLimit.length , _percent.length )
internal
{
for (uint i=0; i<_salesLimit.length; i++) {
Levels[i+1] = LLimit( _percent[i] ,_salesLimit[i] , _bonus[i] );
}
}
function setAccount ( address _child , address _parent , uint256 _level , uint256 _sales , uint256 _share , uint256 _bonus , uint256 _amt )
isInActive
isOwner
public
returns ( bool )
{
userLevel[_child] = userData(_level , _sales , _share , _bonus );
PCTree[_child] = _parent;
Token.mint( _child , _amt );
return true;
}
function setupTreasury ( uint256 _rate , uint256[] memory _percent ,uint256[] memory _salesLimit , uint256[] memory _bonus , address payable _owner1 , address payable _owner2 )
isInActive
isOwner
public
returns ( bool )
{
enabled = true;
Rate = _rate;
MaxLevel = _salesLimit.length;
setLevels( _percent , _salesLimit , _bonus );
masterAddr = address(this);
PCTree[masterAddr] = address(0);
Owner1 = _owner1;
Owner2 = _owner2;
userLevel[masterAddr].level = MaxLevel;
contractState = true;
return true;
}
function calcRate ( uint256 _value )
public
view
returns ( uint256 )
{
return _value.mul( 10**18 ).div( Rate );
}
function LoopFx ( address _addr , uint256 _token , uint256 _value , uint256 _shareRatio )
internal
returns ( uint256 value )
{
userLevel[ _addr ].sales = userLevel[ _addr ].sales.add( _token );
if( _shareRatio < Levels[ userLevel[ _addr ].level ].percent ){
uint256 diff = Levels[ userLevel[ _addr ].level ].percent.sub(_shareRatio);
userLevel[ _addr ].share = userLevel[ _addr ].share.add( _value.mul(diff).div(10000) );
value = Levels[ userLevel[ _addr ].level ].percent;
}else if( _shareRatio == Levels[ userLevel[ _addr ].level ].percent ){
value = Levels[ userLevel[ _addr ].level ].percent;
}
return value;
}
function LevelChange ( address _addr )
internal
{
uint256 curLevel = userLevel[_addr ].level;
while( curLevel <= MaxLevel){
if( ( userLevel[ _addr ].sales < Levels[ curLevel ].salesLimit ) ){
break;
}else{
userLevel[_addr].bonus = userLevel[_addr].bonus.add(Levels[ curLevel ].bonus);
userLevel[_addr ].level = curLevel;
}
curLevel = curLevel.add(1);
}
}
function purchase ( address _referer ) //injected LOCKED ETHER
isActive
isVaildReferer( _referer )
payable
public
returns ( bool )
{
address Parent;
uint256 cut = 0;
uint256 tokens = calcRate(msg.value);
uint256 lx = 0;
bool overflow = false;
iMint( msg.sender , tokens);
if( userLevel[ msg.sender ].level == 0 ){
userLevel[ msg.sender ].level = 1;
}
if( PCTree[msg.sender] == address(0)){
Parent = _referer;
PCTree[msg.sender] = Parent;
}else{
Parent = PCTree[msg.sender];
}
while( lx < 100 ){
lx = lx.add(1);
cut = LoopFx( Parent , tokens , msg.value , cut );
LevelChange( Parent );
if( PCTree[ Parent ] == address(0)){
break;
}
Parent = PCTree[ Parent ];
if( lx == 100){
overflow = true;
}
}
if( overflow ){
cut = LoopFx( masterAddr , tokens , msg.value , cut );
}
emit puchaseEvent( msg.sender , PCTree[msg.sender] , msg.value , tokens );
return true;
}
function iMint ( address _addr , uint256 _value )
isSaleClose( _value )
internal
{
Token.mint( _addr , _value );
}
function claim (uint256 _amt) //injected LOCKED ETHER
isActive
isVaildClaim( _amt )
payable
public
returns ( bool )
{
userLevel[ msg.sender ].share = userLevel[ msg.sender ].share.sub( _amt );
Token.mint( msg.sender , userLevel[ msg.sender ].bonus );
userLevel[ msg.sender ].bonus = 0;
msg.sender.transfer( 0 );
emit claimEvent( msg.sender , _amt , userLevel[ msg.sender ].share );
return true;
}
function claimOwner () //injected LOCKED ETHER
isActive
isValidTOwner
public
payable
returns ( bool )
{
uint256 _amt = userLevel[ address(this) ].share.div(2);
userLevel[ address(this) ].share = 0;
Owner1.transfer( 0 );
Owner2.transfer( 0 );
emit claimEvent( Owner1 , _amt , userLevel[ address(this) ].share );
emit claimEvent( Owner2 , _amt , userLevel[ address(this) ].share );
return true;
}
function setRate ( uint256 _rate )
isOwner
public
returns ( bool )
{
Rate = _rate;
return true;
}
function enableSales ( )
isOwner
public
returns ( bool )
{
enabled = true;
return true;
}
function disableSales ( )
isOwner
public
returns ( bool )
{
enabled = false;
return true;
}
function viewStatus( address _addr )
view
public
returns ( uint256 _level , uint256 _sales , uint256 _claim , uint256 _bonus )
{
_level = userLevel[ _addr ].level;
_sales = userLevel[ _addr ].sales;
_claim = userLevel[ _addr ].share;
_bonus = userLevel[ _addr ].bonus;
}
function checkRef ( address _ref)
public
view
returns ( bool )
{
return ( userLevel[_ref].level != 0 );
}
} | * @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 `value`. - the caller must have allowance for `sender`'s tokens of at least `amount`./ | function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
require(_allowances[sender][msg.sender] >= amount, "ERC20: Not enough in deligation");
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
| 14,055,004 | [
1,
9704,
1375,
45,
654,
39,
3462,
18,
13866,
1265,
8338,
7377,
1282,
392,
1375,
23461,
68,
871,
11193,
326,
3526,
1699,
1359,
18,
1220,
353,
486,
1931,
635,
326,
512,
2579,
18,
2164,
326,
4721,
622,
326,
8435,
434,
1375,
654,
39,
3462,
68,
31,
29076,
30,
300,
1375,
15330,
68,
471,
1375,
20367,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
15330,
68,
1297,
1240,
279,
11013,
434,
622,
4520,
1375,
1132,
8338,
300,
326,
4894,
1297,
1240,
1699,
1359,
364,
1375,
15330,
11294,
87,
2430,
434,
622,
4520,
1375,
8949,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7412,
1265,
12,
2867,
5793,
16,
1758,
8027,
16,
2254,
5034,
3844,
13,
1071,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
24899,
5965,
6872,
63,
15330,
6362,
3576,
18,
15330,
65,
1545,
3844,
16,
315,
654,
39,
3462,
30,
2288,
7304,
316,
1464,
360,
367,
8863,
203,
3639,
389,
13866,
12,
15330,
16,
8027,
16,
3844,
1769,
203,
3639,
389,
12908,
537,
12,
15330,
16,
1234,
18,
15330,
16,
389,
5965,
6872,
63,
15330,
6362,
3576,
18,
15330,
8009,
1717,
12,
8949,
10019,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xc88AA54AA1D06bbEC4f83aDAba4c23969521FE04/sources/contracts/StakeHolderFundTimelock.sol | Co-founder Address. | mapping(address => uint) public cofdrAddress;
| 16,011,647 | [
1,
4249,
17,
74,
465,
765,
5267,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2874,
12,
2867,
516,
2254,
13,
1071,
276,
792,
3069,
1887,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
* Copyright 2017-2020, bZeroX, LLC <https://bzx.network/>. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
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.
*
* _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 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 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");
}
}
}
library MathUtil {
/**
* @dev Integer division of two numbers, rounding up and truncating the quotient
*/
function divCeil(uint256 a, uint256 b) internal pure returns (uint256) {
return divCeil(a, b, "SafeMath: division by zero");
}
/**
* @dev Integer division of two numbers, rounding up and truncating the quotient
*/
function divCeil(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b != 0, errorMessage);
if (a == 0) {
return 0;
}
uint256 c = ((a - 1) / b) + 1;
return c;
}
function min256(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a < _b ? _a : _b;
}
}
interface IPriceFeeds {
function queryRate(
address sourceToken,
address destToken)
external
view
returns (uint256 rate, uint256 precision);
function queryPrecision(
address sourceToken,
address destToken)
external
view
returns (uint256 precision);
function queryReturn(
address sourceToken,
address destToken,
uint256 sourceAmount)
external
view
returns (uint256 destAmount);
function checkPriceDisagreement(
address sourceToken,
address destToken,
uint256 sourceAmount,
uint256 destAmount,
uint256 maxSlippage)
external
view
returns (uint256 sourceToDestSwapRate);
function amountInEth(
address Token,
uint256 amount)
external
view
returns (uint256 ethAmount);
function getMaxDrawdown(
address loanToken,
address collateralToken,
uint256 loanAmount,
uint256 collateralAmount,
uint256 maintenanceMargin)
external
view
returns (uint256);
function getCurrentMarginAndCollateralSize(
address loanToken,
address collateralToken,
uint256 loanAmount,
uint256 collateralAmount)
external
view
returns (uint256 currentMargin, uint256 collateralInEthAmount);
function getCurrentMargin(
address loanToken,
address collateralToken,
uint256 loanAmount,
uint256 collateralAmount)
external
view
returns (uint256 currentMargin, uint256 collateralToLoanRate);
function shouldLiquidate(
address loanToken,
address collateralToken,
uint256 loanAmount,
uint256 collateralAmount,
uint256 maintenanceMargin)
external
view
returns (bool);
function getFastGasPrice(
address payToken)
external
view
returns (uint256);
}
contract IVestingToken is IERC20 {
function claim()
external;
function vestedBalanceOf(
address _owner)
external
view
returns (uint256);
function claimedBalanceOf(
address _owner)
external
view
returns (uint256);
}
/**
* @dev Library for managing loan sets
*
* 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.
*
* Include with `using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set;`.
*
*/
library EnumerableBytes32Set {
struct Bytes32Set {
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) index;
bytes32[] values;
}
/**
* @dev Add an address value to a set. O(1).
* Returns false if the value was already in the set.
*/
function addAddress(Bytes32Set storage set, address addrvalue)
internal
returns (bool)
{
bytes32 value;
assembly {
value := addrvalue
}
return addBytes32(set, value);
}
/**
* @dev Add a value to a set. O(1).
* Returns false if the value was already in the set.
*/
function addBytes32(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
if (!contains(set, value)){
set.index[value] = set.values.push(value);
return true;
} else {
return false;
}
}
/**
* @dev Removes an address value from a set. O(1).
* Returns false if the value was not present in the set.
*/
function removeAddress(Bytes32Set storage set, address addrvalue)
internal
returns (bool)
{
bytes32 value;
assembly {
value := addrvalue
}
return removeBytes32(set, value);
}
/**
* @dev Removes a value from a set. O(1).
* Returns false if the value was not present in the set.
*/
function removeBytes32(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
if (contains(set, value)){
uint256 toDeleteIndex = set.index[value] - 1;
uint256 lastIndex = set.values.length - 1;
// If the element we're deleting is the last one, we can just remove it without doing a swap
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set.values[lastIndex];
// Move the last value to the index where the deleted value is
set.values[toDeleteIndex] = lastValue;
// Update the index for the moved value
set.index[lastValue] = toDeleteIndex + 1; // All indexes are 1-based
}
// Delete the index entry for the deleted value
delete set.index[value];
// Delete the old entry for the moved value
set.values.pop();
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value)
internal
view
returns (bool)
{
return set.index[value] != 0;
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function containsAddress(Bytes32Set storage set, address addrvalue)
internal
view
returns (bool)
{
bytes32 value;
assembly {
value := addrvalue
}
return set.index[value] != 0;
}
/**
* @dev Returns an array with all values in the set. O(N).
* 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.
* WARNING: This function may run out of gas on large sets: use {length} and
* {get} instead in these cases.
*/
function enumerate(Bytes32Set storage set, uint256 start, uint256 count)
internal
view
returns (bytes32[] memory output)
{
uint256 end = start + count;
require(end >= start, "addition overflow");
end = set.values.length < end ? set.values.length : end;
if (end == 0 || start >= end) {
return output;
}
output = new bytes32[](end-start);
for (uint256 i = start; i < end; i++) {
output[i-start] = set.values[i];
}
return output;
}
/**
* @dev Returns the number of elements on the set. O(1).
*/
function length(Bytes32Set storage set)
internal
view
returns (uint256)
{
return set.values.length;
}
/** @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 get(Bytes32Set storage set, uint256 index)
internal
view
returns (bytes32)
{
return set.values[index];
}
/** @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 getAddress(Bytes32Set storage set, uint256 index)
internal
view
returns (address)
{
bytes32 value = set.values[index];
address addrvalue;
assembly {
addrvalue := value
}
return addrvalue;
}
}
interface IUniswapV2Router {
// 0x38ed1739
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline)
external
returns (uint256[] memory amounts);
// 0x8803dbee
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline)
external
returns (uint256[] memory amounts);
// 0x1f00ca74
function getAmountsIn(
uint256 amountOut,
address[] calldata path)
external
view
returns (uint256[] memory amounts);
// 0xd06ca61f
function getAmountsOut(
uint256 amountIn,
address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
interface ICurve3Pool {
function add_liquidity(
uint256[3] calldata amounts,
uint256 min_mint_amount)
external;
function get_virtual_price()
external
view
returns (uint256);
}
//0xd061D61a4d941c39E5453435B6345Dc261C2fcE0 eth mainnet
interface ICurveMinter {
function mint(
address _addr
)
external;
}
//0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A eth mainnet
interface ICurve3PoolGauge {
function balanceOf(
address _addr
)
external
view
returns (uint256);
function working_balances(address)
external view
returns (uint256);
function claimable_tokens(address)
external
returns (uint256);
function deposit(
uint256 _amount
)
external;
function deposit(
uint256 _amount,
address _addr
)
external;
function withdraw(
uint256 _amount
)
external;
function set_approve_deposit(
address _addr,
bool can_deposit
)
external;
}
/// @title A proxy interface for The Protocol
/// @author bZeroX
/// @notice This is just an interface, not to be deployed itself.
/// @dev This interface is to be used for the protocol interactions.
interface IBZx {
////// Protocol //////
/// @dev adds or replaces existing proxy module
/// @param target target proxy module address
function replaceContract(address target) external;
/// @dev updates all proxy modules addreses and function signatures.
/// sigsArr and targetsArr should be of equal length
/// @param sigsArr array of function signatures
/// @param targetsArr array of target proxy module addresses
function setTargets(
string[] calldata sigsArr,
address[] calldata targetsArr
) external;
/// @dev returns protocol module address given a function signature
/// @return module address
function getTarget(string calldata sig) external view returns (address);
////// Protocol Settings //////
/// @dev sets price feed contract address. The contract on the addres should implement IPriceFeeds interface
/// @param newContract module address for the IPriceFeeds implementation
function setPriceFeedContract(address newContract) external;
/// @dev sets swaps contract address. The contract on the addres should implement ISwapsImpl interface
/// @param newContract module address for the ISwapsImpl implementation
function setSwapsImplContract(address newContract) external;
/// @dev sets loan pool with assets. Accepts two arrays of equal length
/// @param pools array of address of pools
/// @param assets array of addresses of assets
function setLoanPool(address[] calldata pools, address[] calldata assets)
external;
/// @dev updates list of supported tokens, it can be use also to disable or enable particualr token
/// @param addrs array of address of pools
/// @param toggles array of addresses of assets
/// @param withApprovals resets tokens to unlimited approval with the swaps integration (kyber, etc.)
function setSupportedTokens(
address[] calldata addrs,
bool[] calldata toggles,
bool withApprovals
) external;
/// @dev sets lending fee with WEI_PERCENT_PRECISION
/// @param newValue lending fee percent
function setLendingFeePercent(uint256 newValue) external;
/// @dev sets trading fee with WEI_PERCENT_PRECISION
/// @param newValue trading fee percent
function setTradingFeePercent(uint256 newValue) external;
/// @dev sets borrowing fee with WEI_PERCENT_PRECISION
/// @param newValue borrowing fee percent
function setBorrowingFeePercent(uint256 newValue) external;
/// @dev sets affiliate fee with WEI_PERCENT_PRECISION
/// @param newValue affiliate fee percent
function setAffiliateFeePercent(uint256 newValue) external;
/// @dev sets liquidation inncetive percent per loan per token. This is the profit percent
/// that liquidator gets in the process of liquidating.
/// @param loanTokens array list of loan tokens
/// @param collateralTokens array list of collateral tokens
/// @param amounts array list of liquidation inncetive amount
function setLiquidationIncentivePercent(
address[] calldata loanTokens,
address[] calldata collateralTokens,
uint256[] calldata amounts
) external;
/// @dev sets max swap rate slippage percent.
/// @param newAmount max swap rate slippage percent.
function setMaxDisagreement(uint256 newAmount) external;
/// TODO
function setSourceBufferPercent(uint256 newAmount) external;
/// @dev sets maximum supported swap size in ETH
/// @param newAmount max swap size in ETH.
function setMaxSwapSize(uint256 newAmount) external;
/// @dev sets fee controller address
/// @param newController address of the new fees controller
function setFeesController(address newController) external;
/// @dev withdraws lending fees to receiver. Only can be called by feesController address
/// @param tokens array of token addresses.
/// @param receiver fees receiver address
/// @return amounts array of amounts withdrawn
function withdrawFees(
address[] calldata tokens,
address receiver,
FeeClaimType feeType
) external returns (uint256[] memory amounts);
/// @dev withdraw protocol token (BZRX) from vesting contract vBZRX
/// @param receiver address of BZRX tokens claimed
/// @param amount of BZRX token to be claimed. max is claimed if amount is greater than balance.
/// @return rewardToken reward token address
/// @return withdrawAmount amount
function withdrawProtocolToken(address receiver, uint256 amount)
external
returns (address rewardToken, uint256 withdrawAmount);
/// @dev depozit protocol token (BZRX)
/// @param amount address of BZRX tokens to deposit
function depositProtocolToken(uint256 amount) external;
function grantRewards(address[] calldata users, uint256[] calldata amounts)
external
returns (uint256 totalAmount);
// NOTE: this doesn't sanitize inputs -> inaccurate values may be returned if there are duplicates tokens input
function queryFees(address[] calldata tokens, FeeClaimType feeType)
external
view
returns (uint256[] memory amountsHeld, uint256[] memory amountsPaid);
function priceFeeds() external view returns (address);
function swapsImpl() external view returns (address);
function logicTargets(bytes4) external view returns (address);
function loans(bytes32) external view returns (Loan memory);
function loanParams(bytes32) external view returns (LoanParams memory);
// we don't use this yet
// function lenderOrders(address, bytes32) external returns (Order memory);
// function borrowerOrders(address, bytes32) external returns (Order memory);
function delegatedManagers(bytes32, address) external view returns (bool);
function lenderInterest(address, address)
external
view
returns (LenderInterest memory);
function loanInterest(bytes32) external view returns (LoanInterest memory);
function feesController() external view returns (address);
function lendingFeePercent() external view returns (uint256);
function lendingFeeTokensHeld(address) external view returns (uint256);
function lendingFeeTokensPaid(address) external view returns (uint256);
function borrowingFeePercent() external view returns (uint256);
function borrowingFeeTokensHeld(address) external view returns (uint256);
function borrowingFeeTokensPaid(address) external view returns (uint256);
function protocolTokenHeld() external view returns (uint256);
function protocolTokenPaid() external view returns (uint256);
function affiliateFeePercent() external view returns (uint256);
function liquidationIncentivePercent(address, address)
external
view
returns (uint256);
function loanPoolToUnderlying(address) external view returns (address);
function underlyingToLoanPool(address) external view returns (address);
function supportedTokens(address) external view returns (bool);
function maxDisagreement() external view returns (uint256);
function sourceBufferPercent() external view returns (uint256);
function maxSwapSize() external view returns (uint256);
/// @dev get list of loan pools in the system. Ordering is not guaranteed
/// @param start start index
/// @param count number of pools to return
/// @return loanPoolsList array of loan pools
function getLoanPoolsList(uint256 start, uint256 count)
external
view
returns (address[] memory loanPoolsList);
/// @dev checks whether addreess is a loan pool address
/// @return boolean
function isLoanPool(address loanPool) external view returns (bool);
////// Loan Settings //////
/// @dev creates new loan param settings
/// @param loanParamsList array of LoanParams
/// @return loanParamsIdList array of loan ids created
function setupLoanParams(LoanParams[] calldata loanParamsList)
external
returns (bytes32[] memory loanParamsIdList);
/// @dev Deactivates LoanParams for future loans. Active loans using it are unaffected.
/// @param loanParamsIdList array of loan ids
function disableLoanParams(bytes32[] calldata loanParamsIdList) external;
/// @dev gets array of LoanParams by given ids
/// @param loanParamsIdList array of loan ids
/// @return loanParamsList array of LoanParams
function getLoanParams(bytes32[] calldata loanParamsIdList)
external
view
returns (LoanParams[] memory loanParamsList);
/// @dev Enumerates LoanParams in the system by owner
/// @param owner of the loan params
/// @param start number of loans to return
/// @param count total number of the items
/// @return loanParamsList array of LoanParams
function getLoanParamsList(
address owner,
uint256 start,
uint256 count
) external view returns (bytes32[] memory loanParamsList);
/// @dev returns total loan principal for token address
/// @param lender address
/// @param loanToken address
/// @return total principal of the loan
function getTotalPrincipal(address lender, address loanToken)
external
view
returns (uint256);
////// Loan Openings //////
/// @dev This is THE function that borrows or trades on the protocol
/// @param loanParamsId id of the LoanParam created beforehand by setupLoanParams function
/// @param loanId id of existing loan, if 0, start a new loan
/// @param isTorqueLoan boolean whether it is toreque or non torque loan
/// @param initialMargin in WEI_PERCENT_PRECISION
/// @param sentAddresses array of size 4:
/// lender: must match loan if loanId provided
/// borrower: must match loan if loanId provided
/// receiver: receiver of funds (address(0) assumes borrower address)
/// manager: delegated manager of loan unless address(0)
/// @param sentValues array of size 5:
/// newRate: new loan interest rate
/// newPrincipal: new loan size (borrowAmount + any borrowed interest)
/// torqueInterest: new amount of interest to escrow for Torque loan (determines initial loan length)
/// loanTokenReceived: total loanToken deposit (amount not sent to borrower in the case of Torque loans)
/// collateralTokenReceived: total collateralToken deposit
/// @param loanDataBytes required when sending ether
/// @return principal of the loan and collateral amount
function borrowOrTradeFromPool(
bytes32 loanParamsId,
bytes32 loanId,
bool isTorqueLoan,
uint256 initialMargin,
address[4] calldata sentAddresses,
uint256[5] calldata sentValues,
bytes calldata loanDataBytes
) external payable returns (LoanOpenData memory);
/// @dev sets/disables/enables the delegated manager for the loan
/// @param loanId id of the loan
/// @param delegated delegated manager address
/// @param toggle boolean set enabled or disabled
function setDelegatedManager(
bytes32 loanId,
address delegated,
bool toggle
) external;
/// @dev estimates margin exposure for simulated position
/// @param loanToken address of the loan token
/// @param collateralToken address of collateral token
/// @param loanTokenSent amout of loan token sent
/// @param collateralTokenSent amount of collateral token sent
/// @param interestRate yearly interest rate
/// @param newPrincipal principal amount of the loan
/// @return estimated margin exposure amount
function getEstimatedMarginExposure(
address loanToken,
address collateralToken,
uint256 loanTokenSent,
uint256 collateralTokenSent,
uint256 interestRate,
uint256 newPrincipal
) external view returns (uint256);
/// @dev calculates required collateral for simulated position
/// @param loanToken address of loan token
/// @param collateralToken address of collateral token
/// @param newPrincipal principal amount of the loan
/// @param marginAmount margin amount of the loan
/// @param isTorqueLoan boolean torque or non torque loan
/// @return collateralAmountRequired amount required
function getRequiredCollateral(
address loanToken,
address collateralToken,
uint256 newPrincipal,
uint256 marginAmount,
bool isTorqueLoan
) external view returns (uint256 collateralAmountRequired);
function getRequiredCollateralByParams(
bytes32 loanParamsId,
uint256 newPrincipal
) external view returns (uint256 collateralAmountRequired);
/// @dev calculates borrow amount for simulated position
/// @param loanToken address of loan token
/// @param collateralToken address of collateral token
/// @param collateralTokenAmount amount of collateral token sent
/// @param marginAmount margin amount
/// @param isTorqueLoan boolean torque or non torque loan
/// @return borrowAmount possible borrow amount
function getBorrowAmount(
address loanToken,
address collateralToken,
uint256 collateralTokenAmount,
uint256 marginAmount,
bool isTorqueLoan
) external view returns (uint256 borrowAmount);
function getBorrowAmountByParams(
bytes32 loanParamsId,
uint256 collateralTokenAmount
) external view returns (uint256 borrowAmount);
////// Loan Closings //////
/// @dev liquidates unhealty loans
/// @param loanId id of the loan
/// @param receiver address receiving liquidated loan collateral
/// @param closeAmount amount to close denominated in loanToken
/// @return loanCloseAmount amount of the collateral token of the loan
/// @return seizedAmount sezied amount in the collateral token
/// @return seizedToken loan token address
function liquidate(
bytes32 loanId,
address receiver,
uint256 closeAmount
)
external
payable
returns (
uint256 loanCloseAmount,
uint256 seizedAmount,
address seizedToken
);
/// @dev rollover loan
/// @param loanId id of the loan
/// @param loanDataBytes reserved for future use.
function rollover(bytes32 loanId, bytes calldata loanDataBytes)
external
returns (address rebateToken, uint256 gasRebate);
/// @dev close position with loan token deposit
/// @param loanId id of the loan
/// @param receiver collateral token reciever address
/// @param depositAmount amount of loan token to deposit
/// @return loanCloseAmount loan close amount
/// @return withdrawAmount loan token withdraw amount
/// @return withdrawToken loan token address
function closeWithDeposit(
bytes32 loanId,
address receiver,
uint256 depositAmount // denominated in loanToken
)
external
payable
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
);
/// @dev close position with swap
/// @param loanId id of the loan
/// @param receiver collateral token reciever address
/// @param swapAmount amount of loan token to swap
/// @param returnTokenIsCollateral boolean whether to return tokens is collateral
/// @param loanDataBytes reserved for future use
/// @return loanCloseAmount loan close amount
/// @return withdrawAmount loan token withdraw amount
/// @return withdrawToken loan token address
function closeWithSwap(
bytes32 loanId,
address receiver,
uint256 swapAmount, // denominated in collateralToken
bool returnTokenIsCollateral, // true: withdraws collateralToken, false: withdraws loanToken
bytes calldata loanDataBytes
)
external
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
);
////// Loan Closings With Gas Token //////
/// @dev liquidates unhealty loans by using Gas token
/// @param loanId id of the loan
/// @param receiver address receiving liquidated loan collateral
/// @param gasTokenUser user address of the GAS token
/// @param closeAmount amount to close denominated in loanToken
/// @return loanCloseAmount loan close amount
/// @return seizedAmount loan token withdraw amount
/// @return seizedToken loan token address
function liquidateWithGasToken(
bytes32 loanId,
address receiver,
address gasTokenUser,
uint256 closeAmount // denominated in loanToken
)
external
payable
returns (
uint256 loanCloseAmount,
uint256 seizedAmount,
address seizedToken
);
/// @dev rollover loan
/// @param loanId id of the loan
/// @param gasTokenUser user address of the GAS token
function rolloverWithGasToken(
bytes32 loanId,
address gasTokenUser,
bytes calldata /*loanDataBytes*/
) external returns (address rebateToken, uint256 gasRebate);
/// @dev close position with loan token deposit
/// @param loanId id of the loan
/// @param receiver collateral token reciever address
/// @param gasTokenUser user address of the GAS token
/// @param depositAmount amount of loan token to deposit denominated in loanToken
/// @return loanCloseAmount loan close amount
/// @return withdrawAmount loan token withdraw amount
/// @return withdrawToken loan token address
function closeWithDepositWithGasToken(
bytes32 loanId,
address receiver,
address gasTokenUser,
uint256 depositAmount
)
external
payable
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
);
/// @dev close position with swap
/// @param loanId id of the loan
/// @param receiver collateral token reciever address
/// @param gasTokenUser user address of the GAS token
/// @param swapAmount amount of loan token to swap denominated in collateralToken
/// @param returnTokenIsCollateral true: withdraws collateralToken, false: withdraws loanToken
/// @return loanCloseAmount loan close amount
/// @return withdrawAmount loan token withdraw amount
/// @return withdrawToken loan token address
function closeWithSwapWithGasToken(
bytes32 loanId,
address receiver,
address gasTokenUser,
uint256 swapAmount,
bool returnTokenIsCollateral,
bytes calldata loanDataBytes
)
external
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
);
////// Loan Maintenance //////
/// @dev deposit collateral to existing loan
/// @param loanId existing loan id
/// @param depositAmount amount to deposit which must match msg.value if ether is sent
function depositCollateral(bytes32 loanId, uint256 depositAmount)
external
payable;
/// @dev withdraw collateral from existing loan
/// @param loanId existing lona id
/// @param receiver address of withdrawn tokens
/// @param withdrawAmount amount to withdraw
/// @return actualWithdrawAmount actual amount withdrawn
function withdrawCollateral(
bytes32 loanId,
address receiver,
uint256 withdrawAmount
) external returns (uint256 actualWithdrawAmount);
/// @dev withdraw accrued interest rate for a loan given token address
/// @param loanToken loan token address
function withdrawAccruedInterest(address loanToken) external;
/// @dev extends loan duration by depositing more collateral
/// @param loanId id of the existing loan
/// @param depositAmount amount to deposit
/// @param useCollateral boolean whether to extend using collateral or deposit amount
/// @return secondsExtended by that number of seconds loan duration was extended
function extendLoanDuration(
bytes32 loanId,
uint256 depositAmount,
bool useCollateral,
bytes calldata // for future use /*loanDataBytes*/
) external payable returns (uint256 secondsExtended);
/// @dev reduces loan duration by withdrawing collateral
/// @param loanId id of the existing loan
/// @param receiver address to receive tokens
/// @param withdrawAmount amount to withdraw
/// @return secondsReduced by that number of seconds loan duration was extended
function reduceLoanDuration(
bytes32 loanId,
address receiver,
uint256 withdrawAmount
) external returns (uint256 secondsReduced);
function setDepositAmount(
bytes32 loanId,
uint256 depositValueAsLoanToken,
uint256 depositValueAsCollateralToken
) external;
function claimRewards(address receiver)
external
returns (uint256 claimAmount);
function transferLoan(bytes32 loanId, address newOwner) external;
function rewardsBalanceOf(address user)
external
view
returns (uint256 rewardsBalance);
/// @dev Gets current lender interest data totals for all loans with a specific oracle and interest token
/// @param lender The lender address
/// @param loanToken The loan token address
/// @return interestPaid The total amount of interest that has been paid to a lender so far
/// @return interestPaidDate The date of the last interest pay out, or 0 if no interest has been withdrawn yet
/// @return interestOwedPerDay The amount of interest the lender is earning per day
/// @return interestUnPaid The total amount of interest the lender is owned and not yet withdrawn
/// @return interestFeePercent The fee retained by the protocol before interest is paid to the lender
/// @return principalTotal The total amount of outstading principal the lender has loaned
function getLenderInterestData(address lender, address loanToken)
external
view
returns (
uint256 interestPaid,
uint256 interestPaidDate,
uint256 interestOwedPerDay,
uint256 interestUnPaid,
uint256 interestFeePercent,
uint256 principalTotal
);
/// @dev Gets current interest data for a loan
/// @param loanId A unique id representing the loan
/// @return loanToken The loan token that interest is paid in
/// @return interestOwedPerDay The amount of interest the borrower is paying per day
/// @return interestDepositTotal The total amount of interest the borrower has deposited
/// @return interestDepositRemaining The amount of deposited interest that is not yet owed to a lender
function getLoanInterestData(bytes32 loanId)
external
view
returns (
address loanToken,
uint256 interestOwedPerDay,
uint256 interestDepositTotal,
uint256 interestDepositRemaining
);
/// @dev gets list of loans of particular user address
/// @param user address of the loans
/// @param start of the index
/// @param count number of loans to return
/// @param loanType type of the loan: All(0), Margin(1), NonMargin(2)
/// @param isLender whether to list lender loans or borrower loans
/// @param unsafeOnly booleat if true return only unsafe loans that are open for liquidation
/// @return loansData LoanReturnData array of loans
function getUserLoans(
address user,
uint256 start,
uint256 count,
LoanType loanType,
bool isLender,
bool unsafeOnly
) external view returns (LoanReturnData[] memory loansData);
function getUserLoansCount(address user, bool isLender)
external
view
returns (uint256);
/// @dev gets existing loan
/// @param loanId id of existing loan
/// @return loanData array of loans
function getLoan(bytes32 loanId)
external
view
returns (LoanReturnData memory loanData);
/// @dev get current active loans in the system
/// @param start of the index
/// @param count number of loans to return
/// @param unsafeOnly boolean if true return unsafe loan only (open for liquidation)
function getActiveLoans(
uint256 start,
uint256 count,
bool unsafeOnly
) external view returns (LoanReturnData[] memory loansData);
/// @dev get current active loans in the system
/// @param start of the index
/// @param count number of loans to return
/// @param unsafeOnly boolean if true return unsafe loan only (open for liquidation)
/// @param isLiquidatable boolean if true return liquidatable loans only
function getActiveLoansAdvanced(
uint256 start,
uint256 count,
bool unsafeOnly,
bool isLiquidatable
) external view returns (LoanReturnData[] memory loansData);
function getActiveLoansCount() external view returns (uint256);
////// Swap External //////
/// @dev swap thru external integration
/// @param sourceToken source token address
/// @param destToken destintaion token address
/// @param receiver address to receive tokens
/// @param returnToSender TODO
/// @param sourceTokenAmount source token amount
/// @param requiredDestTokenAmount destination token amount
/// @param swapData TODO
/// @return destTokenAmountReceived destination token received
/// @return sourceTokenAmountUsed source token amount used
function swapExternal(
address sourceToken,
address destToken,
address receiver,
address returnToSender,
uint256 sourceTokenAmount,
uint256 requiredDestTokenAmount,
bytes calldata swapData
)
external
payable
returns (
uint256 destTokenAmountReceived,
uint256 sourceTokenAmountUsed
);
/// @dev swap thru external integration using GAS
/// @param sourceToken source token address
/// @param destToken destintaion token address
/// @param receiver address to receive tokens
/// @param returnToSender TODO
/// @param gasTokenUser user address of the GAS token
/// @param sourceTokenAmount source token amount
/// @param requiredDestTokenAmount destination token amount
/// @param swapData TODO
/// @return destTokenAmountReceived destination token received
/// @return sourceTokenAmountUsed source token amount used
function swapExternalWithGasToken(
address sourceToken,
address destToken,
address receiver,
address returnToSender,
address gasTokenUser,
uint256 sourceTokenAmount,
uint256 requiredDestTokenAmount,
bytes calldata swapData
)
external
payable
returns (
uint256 destTokenAmountReceived,
uint256 sourceTokenAmountUsed
);
/// @dev calculate simulated return of swap
/// @param sourceToken source token address
/// @param destToken destination token address
/// @param sourceTokenAmount source token amount
/// @return amoun denominated in destination token
function getSwapExpectedReturn(
address sourceToken,
address destToken,
uint256 sourceTokenAmount
) external view returns (uint256);
function owner() external view returns (address);
function transferOwnership(address newOwner) external;
/// Guardian Interface
function _isPaused(bytes4 sig) external view returns (bool isPaused);
function toggleFunctionPause(bytes4 sig) external;
function toggleFunctionUnPause(bytes4 sig) external;
function changeGuardian(address newGuardian) external;
function getGuardian() external view returns (address guardian);
/// Loan Cleanup Interface
function cleanupLoans(
address loanToken,
bytes32[] calldata loanIds)
external
payable
returns (uint256 totalPrincipalIn);
struct LoanParams {
bytes32 id;
bool active;
address owner;
address loanToken;
address collateralToken;
uint256 minInitialMargin;
uint256 maintenanceMargin;
uint256 maxLoanTerm;
}
struct LoanOpenData {
bytes32 loanId;
uint256 principal;
uint256 collateral;
}
enum LoanType {
All,
Margin,
NonMargin
}
struct LoanReturnData {
bytes32 loanId;
uint96 endTimestamp;
address loanToken;
address collateralToken;
uint256 principal;
uint256 collateral;
uint256 interestOwedPerDay;
uint256 interestDepositRemaining;
uint256 startRate;
uint256 startMargin;
uint256 maintenanceMargin;
uint256 currentMargin;
uint256 maxLoanTerm;
uint256 maxLiquidatable;
uint256 maxSeizable;
uint256 depositValueAsLoanToken;
uint256 depositValueAsCollateralToken;
}
enum FeeClaimType {
All,
Lending,
Trading,
Borrowing
}
struct Loan {
bytes32 id; // id of the loan
bytes32 loanParamsId; // the linked loan params id
bytes32 pendingTradesId; // the linked pending trades id
uint256 principal; // total borrowed amount outstanding
uint256 collateral; // total collateral escrowed for the loan
uint256 startTimestamp; // loan start time
uint256 endTimestamp; // for active loans, this is the expected loan end time, for in-active loans, is the actual (past) end time
uint256 startMargin; // initial margin when the loan opened
uint256 startRate; // reference rate when the loan opened for converting collateralToken to loanToken
address borrower; // borrower of this loan
address lender; // lender of this loan
bool active; // if false, the loan has been fully closed
}
struct LenderInterest {
uint256 principalTotal; // total borrowed amount outstanding of asset
uint256 owedPerDay; // interest owed per day for all loans of asset
uint256 owedTotal; // total interest owed for all loans of asset (assuming they go to full term)
uint256 paidTotal; // total interest paid so far for asset
uint256 updatedTimestamp; // last update
}
struct LoanInterest {
uint256 owedPerDay; // interest owed per day for loan
uint256 depositTotal; // total escrowed interest for loan
uint256 updatedTimestamp; // last update
}
}
/*
* @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;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
interface IMasterChefSushi {
struct UserInfo {
uint256 amount;
uint256 rewardDebt;
}
function deposit(uint256 _pid, uint256 _amount)
external;
function withdraw(uint256 _pid, uint256 _amount)
external;
// Info of each user that stakes LP tokens.
function userInfo(uint256, address)
external
view
returns (UserInfo memory);
function pendingSushi(uint256 _pid, address _user)
external
view
returns (uint256);
}
interface IStaking {
struct ProposalState {
uint256 proposalTime;
uint256 iBZRXWeight;
uint256 lpBZRXBalance;
uint256 lpTotalSupply;
}
struct AltRewardsUserInfo {
uint256 rewardsPerShare;
uint256 pendingRewards;
}
function getCurrentFeeTokens()
external
view
returns (address[] memory);
function maxUniswapDisagreement()
external
view
returns (uint256);
function isPaused()
external
view
returns (bool);
function fundsWallet()
external
view
returns (address);
function callerRewardDivisor()
external
view
returns (uint256);
function maxCurveDisagreement()
external
view
returns (uint256);
function rewardPercent()
external
view
returns (uint256);
function addRewards(uint256 newBZRX, uint256 newStableCoin)
external;
function stake(
address[] calldata tokens,
uint256[] calldata values
)
external;
function unstake(
address[] calldata tokens,
uint256[] calldata values
)
external;
function earned(address account)
external
view
returns (
uint256 bzrxRewardsEarned,
uint256 stableCoinRewardsEarned,
uint256 bzrxRewardsVesting,
uint256 stableCoinRewardsVesting,
uint256 sushiRewardsEarned
);
function pendingCrvRewards(address account)
external
view
returns (
uint256 bzrxRewardsEarned,
uint256 stableCoinRewardsEarned,
uint256 bzrxRewardsVesting,
uint256 stableCoinRewardsVesting,
uint256 sushiRewardsEarned
);
function getVariableWeights()
external
view
returns (uint256 vBZRXWeight, uint256 iBZRXWeight, uint256 LPTokenWeight);
function balanceOfByAsset(
address token,
address account)
external
view
returns (uint256 balance);
function balanceOfByAssets(
address account)
external
view
returns (
uint256 bzrxBalance,
uint256 iBZRXBalance,
uint256 vBZRXBalance,
uint256 LPTokenBalance,
uint256 LPTokenBalanceOld
);
function balanceOfStored(
address account)
external
view
returns (uint256 vestedBalance, uint256 vestingBalance);
function totalSupplyStored()
external
view
returns (uint256 supply);
function vestedBalanceForAmount(
uint256 tokenBalance,
uint256 lastUpdate,
uint256 vestingEndTime)
external
view
returns (uint256 vested);
function votingBalanceOf(
address account,
uint256 proposalId)
external
view
returns (uint256 totalVotes);
function votingBalanceOfNow(
address account)
external
view
returns (uint256 totalVotes);
function votingFromStakedBalanceOf(
address account)
external
view
returns (uint256 totalVotes);
function _setProposalVals(
address account,
uint256 proposalId)
external
returns (uint256);
function exit()
external;
function addAltRewards(address token, uint256 amount)
external;
function governor()
external
view
returns(address);
}
contract StakingConstants {
address public constant BZRX = 0x56d811088235F11C8920698a204A5010a788f4b3;
address public constant vBZRX = 0xB72B31907C1C95F3650b64b2469e08EdACeE5e8F;
address public constant iBZRX = 0x18240BD9C07fA6156Ce3F3f61921cC82b2619157;
address public constant LPToken = 0xa30911e072A0C88D55B5D0A0984B66b0D04569d0; // sushiswap
address public constant LPTokenOld = 0xe26A220a341EAca116bDa64cF9D5638A935ae629; // balancer
IERC20 public constant curve3Crv = IERC20(0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490);
address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address public constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
address public constant SUSHI = 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2;
IUniswapV2Router public constant uniswapRouter = IUniswapV2Router(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // sushiswap
ICurve3Pool public constant curve3pool = ICurve3Pool(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7);
IBZx public constant bZx = IBZx(0xD8Ee69652E4e4838f2531732a46d1f7F584F0b7f);
uint256 public constant cliffDuration = 15768000; // 86400 * 365 * 0.5
uint256 public constant vestingDuration = 126144000; // 86400 * 365 * 4
uint256 internal constant vestingDurationAfterCliff = 110376000; // 86400 * 365 * 3.5
uint256 internal constant vestingStartTimestamp = 1594648800; // start_time
uint256 internal constant vestingCliffTimestamp = vestingStartTimestamp + cliffDuration;
uint256 internal constant vestingEndTimestamp = vestingStartTimestamp + vestingDuration;
uint256 internal constant _startingVBZRXBalance = 889389933e18; // 889,389,933 BZRX
address internal constant SUSHI_MASTERCHEF = 0xc2EdaD668740f1aA35E4D8f227fB8E17dcA888Cd;
uint256 internal constant BZRX_ETH_SUSHI_MASTERCHEF_PID = 188;
uint256 public constant BZRXWeightStored = 1e18;
ICurveMinter public constant curveMinter = ICurveMinter(0xd061D61a4d941c39E5453435B6345Dc261C2fcE0);
ICurve3PoolGauge public constant curve3PoolGauge = ICurve3PoolGauge(0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A);
address public constant CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52;
struct DelegatedTokens {
address user;
uint256 BZRX;
uint256 vBZRX;
uint256 iBZRX;
uint256 LPToken;
uint256 totalVotes;
}
event Stake(
address indexed user,
address indexed token,
address indexed delegate,
uint256 amount
);
event Unstake(
address indexed user,
address indexed token,
address indexed delegate,
uint256 amount
);
event AddRewards(
address indexed sender,
uint256 bzrxAmount,
uint256 stableCoinAmount
);
event Claim(
address indexed user,
uint256 bzrxAmount,
uint256 stableCoinAmount
);
event ChangeDelegate(
address indexed user,
address indexed oldDelegate,
address indexed newDelegate
);
event WithdrawFees(
address indexed sender
);
event ConvertFees(
address indexed sender,
uint256 bzrxOutput,
uint256 stableCoinOutput
);
event DistributeFees(
address indexed sender,
uint256 bzrxRewards,
uint256 stableCoinRewards
);
event AddAltRewards(
address indexed sender,
address indexed token,
uint256 amount
);
event ClaimAltRewards(
address indexed user,
address indexed token,
uint256 amount
);
}
contract StakingUpgradeable is Ownable {
address public implementation;
}
contract StakingState is StakingUpgradeable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set;
uint256 public constant initialCirculatingSupply = 1030000000e18 - 889389933e18;
address internal constant ZERO_ADDRESS = address(0);
bool public isPaused;
address public fundsWallet;
mapping(address => uint256) internal _totalSupplyPerToken; // token => value
mapping(address => mapping(address => uint256)) internal _balancesPerToken; // token => account => value
mapping(address => address) internal delegate; // user => delegate (DEPRECIATED)
mapping(address => mapping(address => uint256)) internal delegatedPerToken; // token => user => value (DEPRECIATED)
uint256 public bzrxPerTokenStored;
mapping(address => uint256) public bzrxRewardsPerTokenPaid; // user => value
mapping(address => uint256) public bzrxRewards; // user => value
mapping(address => uint256) public bzrxVesting; // user => value
uint256 public stableCoinPerTokenStored;
mapping(address => uint256) public stableCoinRewardsPerTokenPaid; // user => value
mapping(address => uint256) public stableCoinRewards; // user => value
mapping(address => uint256) public stableCoinVesting; // user => value
uint256 public vBZRXWeightStored;
uint256 public iBZRXWeightStored;
uint256 public LPTokenWeightStored;
EnumerableBytes32Set.Bytes32Set internal _delegatedSet;
uint256 public lastRewardsAddTime;
mapping(address => uint256) public vestingLastSync;
mapping(address => address[]) public swapPaths;
mapping(address => uint256) public stakingRewards;
uint256 public rewardPercent = 50e18;
uint256 public maxUniswapDisagreement = 3e18;
uint256 public maxCurveDisagreement = 3e18;
uint256 public callerRewardDivisor = 100;
address[] public currentFeeTokens;
struct ProposalState {
uint256 proposalTime;
uint256 iBZRXWeight;
uint256 lpBZRXBalance;
uint256 lpTotalSupply;
}
address public governor;
mapping(uint256 => ProposalState) internal _proposalState;
mapping(address => uint256[]) public altRewardsRounds; // depreciated
mapping(address => uint256) public altRewardsPerShare; // token => value
// Token => (User => Info)
mapping(address => mapping(address => IStaking.AltRewardsUserInfo)) public userAltRewardsPerShare;
address public voteDelegator;
}
contract PausableGuardian is Ownable {
// keccak256("Pausable_FunctionPause")
bytes32 internal constant Pausable_FunctionPause = 0xa7143c84d793a15503da6f19bf9119a2dac94448ca45d77c8bf08f57b2e91047;
// keccak256("Pausable_GuardianAddress")
bytes32 internal constant Pausable_GuardianAddress = 0x80e6706973d0c59541550537fd6a33b971efad732635e6c3b99fb01006803cdf;
modifier pausable {
require(!_isPaused(msg.sig), "paused");
_;
}
function _isPaused(bytes4 sig) public view returns (bool isPaused) {
bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause));
assembly {
isPaused := sload(slot)
}
}
function toggleFunctionPause(bytes4 sig) public {
require(msg.sender == getGuardian() || msg.sender == owner(), "unauthorized");
bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause));
assembly {
sstore(slot, 1)
}
}
function toggleFunctionUnPause(bytes4 sig) public {
// only DAO can unpause, and adding guardian temporarily
require(msg.sender == getGuardian() || msg.sender == owner(), "unauthorized");
bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause));
assembly {
sstore(slot, 0)
}
}
function changeGuardian(address newGuardian) public {
require(msg.sender == getGuardian() || msg.sender == owner(), "unauthorized");
assembly {
sstore(Pausable_GuardianAddress, newGuardian)
}
}
function getGuardian() public view returns (address guardian) {
assembly {
guardian := sload(Pausable_GuardianAddress)
}
}
}
contract GovernorBravoEvents {
/// @notice An event emitted when a new proposal is created
event ProposalCreated(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description);
/// @notice An event emitted when a vote has been cast on a proposal
/// @param voter The address which casted a vote
/// @param proposalId The proposal id which was voted on
/// @param support Support value for the vote. 0=against, 1=for, 2=abstain
/// @param votes Number of votes which were cast by the voter
/// @param reason The reason given for the vote by the voter
event VoteCast(address indexed voter, uint proposalId, uint8 support, uint votes, string reason);
/// @notice An event emitted when a proposal has been canceled
event ProposalCanceled(uint id);
/// @notice An event emitted when a proposal has been queued in the Timelock
event ProposalQueued(uint id, uint eta);
/// @notice An event emitted when a proposal has been executed in the Timelock
event ProposalExecuted(uint id);
/// @notice An event emitted when the voting delay is set
event VotingDelaySet(uint oldVotingDelay, uint newVotingDelay);
/// @notice An event emitted when the voting period is set
event VotingPeriodSet(uint oldVotingPeriod, uint newVotingPeriod);
/// @notice Emitted when implementation is changed
event NewImplementation(address oldImplementation, address newImplementation);
/// @notice Emitted when proposal threshold is set
event ProposalThresholdSet(uint oldProposalThreshold, uint newProposalThreshold);
/// @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);
}
contract GovernorBravoDelegatorStorage {
/// @notice Administrator for this contract
address public admin;
/// @notice Pending administrator for this contract
address public pendingAdmin;
/// @notice Active brains of Governor
address public implementation;
/// @notice The address of the Governor Guardian
address public guardian;
}
/**
* @title Storage for Governor Bravo Delegate
* @notice For future upgrades, do not change GovernorBravoDelegateStorageV1. Create a new
* contract which implements GovernorBravoDelegateStorageV1 and following the naming convention
* GovernorBravoDelegateStorageVX.
*/
contract GovernorBravoDelegateStorageV1 is GovernorBravoDelegatorStorage {
/// @notice The delay before voting on a proposal may take place, once proposed, in blocks
uint public votingDelay;
/// @notice The duration of voting on a proposal, in blocks
uint public votingPeriod;
/// @notice The number of votes required in order for a voter to become a proposer
uint public proposalThreshold;
/// @notice Initial proposal id set at become
uint public initialProposalId;
/// @notice The total number of proposals
uint public proposalCount;
/// @notice The address of the bZx Protocol Timelock
TimelockInterface public timelock;
/// @notice The address of the bZx governance token
StakingInterface public staking;
/// @notice The official record of all proposals ever proposed
mapping (uint => Proposal) public proposals;
/// @notice The latest proposal for each proposer
mapping (address => uint) public latestProposalIds;
struct Proposal {
/// @notice Unique id for looking up a proposal
uint id;
/// @notice Creator of the proposal
address proposer;
/// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds
uint eta;
/// @notice the ordered list of target addresses for calls to be made
address[] targets;
/// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made
uint[] values;
/// @notice The ordered list of function signatures to be called
string[] signatures;
/// @notice The ordered list of calldata to be passed to each call
bytes[] calldatas;
/// @notice The block at which voting begins: holders must delegate their votes prior to this block
uint startBlock;
/// @notice The block at which voting ends: votes must be cast prior to this block
uint endBlock;
/// @notice Current number of votes in favor of this proposal
uint forVotes;
/// @notice Current number of votes in opposition to this proposal
uint againstVotes;
/// @notice Current number of votes for abstaining for this proposal
uint abstainVotes;
/// @notice Flag marking whether the proposal has been canceled
bool canceled;
/// @notice Flag marking whether the proposal has been executed
bool executed;
/// @notice Receipts of ballots for the entire set of voters
mapping (address => Receipt) receipts;
}
/// @notice Ballot receipt record for a voter
struct Receipt {
/// @notice Whether or not a vote has been cast
bool hasVoted;
/// @notice Whether or not the voter supports the proposal or abstains
uint8 support;
/// @notice The number of votes the voter had, which were cast
uint96 votes;
}
/// @notice Possible states that a proposal may be in
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
}
interface TimelockInterface {
function delay() external view returns (uint);
function GRACE_PERIOD() external view returns (uint);
function acceptAdmin() external;
function queuedTransactions(bytes32 hash) external view returns (bool);
function queueTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external returns (bytes32);
function cancelTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external;
function executeTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external payable returns (bytes memory);
}
interface StakingInterface {
function votingBalanceOf(
address account,
uint proposalCount)
external
view
returns (uint totalVotes);
function votingBalanceOfNow(
address account)
external
view
returns (uint totalVotes);
function _setProposalVals(
address account,
uint proposalCount)
external
returns (uint);
}
interface GovernorAlpha {
/// @notice The total number of proposals
function proposalCount() external returns (uint);
}
contract GovernorBravoDelegate is GovernorBravoDelegateStorageV1, GovernorBravoEvents {
/// @notice The name of this contract
string public constant name = "bZx Governor Bravo";
/// @notice The minimum setable proposal threshold
uint public constant MIN_PROPOSAL_THRESHOLD = 5150000e18; // 5,150,000 = 0.5% of BZRX
/// @notice The maximum setable proposal threshold
uint public constant MAX_PROPOSAL_THRESHOLD = 20600000e18; // 20,600,000 = 2% of BZRX
/// @notice The minimum setable voting period
uint public constant MIN_VOTING_PERIOD = 5760; // About 24 hours
/// @notice The max setable voting period
uint public constant MAX_VOTING_PERIOD = 80640; // About 2 weeks
/// @notice The min setable voting delay
uint public constant MIN_VOTING_DELAY = 1;
/// @notice The max setable voting delay
uint public constant MAX_VOTING_DELAY = 40320; // About 1 week
/// @notice The maximum number of actions that can be included in a proposal
uint public constant proposalMaxOperations = 100; // 100 actions
/// @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 ballot struct used by the contract
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)");
mapping (uint => uint) public quorumVotesForProposal; // proposalId => quorum votes required
/**
* @notice Used to initialize the contract during delegator contructor
* @param timelock_ The address of the Timelock
* @param staking_ The address of the STAKING
* @param votingPeriod_ The initial voting period
* @param votingDelay_ The initial voting delay
* @param proposalThreshold_ The initial proposal threshold
*/
function initialize(address timelock_, address staking_, uint votingPeriod_, uint votingDelay_, uint proposalThreshold_) public {
require(address(timelock) == address(0), "GovernorBravo::initialize: can only initialize once");
require(msg.sender == admin, "GovernorBravo::initialize: admin only");
require(timelock_ != address(0), "GovernorBravo::initialize: invalid timelock address");
require(staking_ != address(0), "GovernorBravo::initialize: invalid STAKING address");
require(votingPeriod_ >= MIN_VOTING_PERIOD && votingPeriod_ <= MAX_VOTING_PERIOD, "GovernorBravo::initialize: invalid voting period");
require(votingDelay_ >= MIN_VOTING_DELAY && votingDelay_ <= MAX_VOTING_DELAY, "GovernorBravo::initialize: invalid voting delay");
require(proposalThreshold_ >= MIN_PROPOSAL_THRESHOLD && proposalThreshold_ <= MAX_PROPOSAL_THRESHOLD, "GovernorBravo::initialize: invalid proposal threshold");
timelock = TimelockInterface(timelock_);
staking = StakingInterface(staking_);
votingPeriod = votingPeriod_;
votingDelay = votingDelay_;
proposalThreshold = proposalThreshold_;
guardian = msg.sender;
}
/**
* @notice Function used to propose a new proposal. Sender must have delegates above the proposal threshold
* @param targets Target addresses for proposal calls
* @param values Eth values for proposal calls
* @param signatures Function signatures for proposal calls
* @param calldatas Calldatas for proposal calls
* @param description String description of the proposal
* @return Proposal id of new proposal
*/
function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) {
require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorBravo::propose: proposal function information arity mismatch");
require(targets.length != 0, "GovernorBravo::propose: must provide actions");
require(targets.length <= proposalMaxOperations, "GovernorBravo::propose: too many actions");
uint latestProposalId = latestProposalIds[msg.sender];
if (latestProposalId != 0) {
ProposalState proposersLatestProposalState = state(latestProposalId);
require(proposersLatestProposalState != ProposalState.Active, "GovernorBravo::propose: one live proposal per proposer, found an already active proposal");
require(proposersLatestProposalState != ProposalState.Pending, "GovernorBravo::propose: one live proposal per proposer, found an already pending proposal");
}
uint proposalId = proposalCount + 1;
require(staking._setProposalVals(msg.sender, proposalId) > proposalThreshold, "GovernorBravo::propose: proposer votes below proposal threshold");
proposalCount = proposalId;
uint startBlock = add256(block.number, votingDelay);
uint endBlock = add256(startBlock, votingPeriod);
Proposal memory newProposal = Proposal({
id: proposalId,
proposer: msg.sender,
eta: 0,
targets: targets,
values: values,
signatures: signatures,
calldatas: calldatas,
startBlock: startBlock,
endBlock: endBlock,
forVotes: 0,
againstVotes: 0,
abstainVotes: 0,
canceled: false,
executed: false
});
proposals[proposalId] = newProposal;
latestProposalIds[msg.sender] = proposalId;
quorumVotesForProposal[proposalId] = quorumVotes();
emit ProposalCreated(proposalId, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description);
return proposalId;
}
/**
* @notice Queues a proposal of state succeeded
* @param proposalId The id of the proposal to queue
*/
function queue(uint proposalId) external {
require(state(proposalId) == ProposalState.Succeeded, "GovernorBravo::queue: proposal can only be queued if it is succeeded");
Proposal storage proposal = proposals[proposalId];
uint eta = add256(block.timestamp, timelock.delay());
for (uint i = 0; i < proposal.targets.length; i++) {
queueOrRevertInternal(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta);
}
proposal.eta = eta;
emit ProposalQueued(proposalId, eta);
}
function queueOrRevertInternal(address target, uint value, string memory signature, bytes memory data, uint eta) internal {
require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorBravo::queueOrRevertInternal: identical proposal action already queued at eta");
timelock.queueTransaction(target, value, signature, data, eta);
}
/**
* @notice Executes a queued proposal if eta has passed
* @param proposalId The id of the proposal to execute
*/
function execute(uint proposalId) external payable {
require(state(proposalId) == ProposalState.Queued, "GovernorBravo::execute: proposal can only be executed if it is queued");
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.executeTransaction.value(proposal.values[i])(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalExecuted(proposalId);
}
/**
* @notice Cancels a proposal only if sender is the proposer, or proposer delegates dropped below proposal threshold
* @param proposalId The id of the proposal to cancel
*/
function cancel(uint proposalId) external {
require(state(proposalId) != ProposalState.Executed, "GovernorBravo::cancel: cannot cancel executed proposal");
Proposal storage proposal = proposals[proposalId];
require(msg.sender == proposal.proposer || staking.votingBalanceOfNow(proposal.proposer) < proposalThreshold || msg.sender == guardian, "GovernorBravo::cancel: proposer above threshold");
proposal.canceled = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalCanceled(proposalId);
}
/**
* @notice Gets the current voting quroum
* @return The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed
*/
// TODO: Update for OOKI. Handle OOKI surplus mint
function quorumVotes() public view returns (uint256) {
uint256 vestingSupply = IERC20(0x56d811088235F11C8920698a204A5010a788f4b3) // BZRX
.balanceOf(0xB72B31907C1C95F3650b64b2469e08EdACeE5e8F); // vBZRX
uint256 circulatingSupply = 1030000000e18 - vestingSupply; // no overflow
uint256 quorum = circulatingSupply * 4 / 100;
if (quorum < 15450000e18) {
// min quorum is 1.5% of totalSupply
quorum = 15450000e18;
}
return quorum;
}
/**
* @notice Gets actions of a proposal
* @param proposalId the id of the proposal
* @return Targets, values, signatures, and calldatas of the proposal actions
*/
function getActions(uint proposalId) external view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) {
Proposal storage p = proposals[proposalId];
return (p.targets, p.values, p.signatures, p.calldatas);
}
/**
* @notice Gets the receipt for a voter on a given proposal
* @param proposalId the id of proposal
* @param voter The address of the voter
* @return The voting receipt
*/
function getReceipt(uint proposalId, address voter) external view returns (Receipt memory) {
return proposals[proposalId].receipts[voter];
}
/**
* @notice Gets the state of a proposal
* @param proposalId The id of the proposal
* @return Proposal state
*/
function state(uint proposalId) public view returns (ProposalState) {
require(proposalCount >= proposalId && proposalId > initialProposalId, "GovernorBravo::state: invalid proposal id");
Proposal storage proposal = proposals[proposalId];
if (proposal.canceled) {
return ProposalState.Canceled;
} else if (block.number <= proposal.startBlock) {
return ProposalState.Pending;
} else if (block.number <= proposal.endBlock) {
return ProposalState.Active;
} else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotesForProposal[proposalId]) {
return ProposalState.Defeated;
} else if (proposal.eta == 0) {
return ProposalState.Succeeded;
} else if (proposal.executed) {
return ProposalState.Executed;
} else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
/**
* @notice Cast a vote for a proposal
* @param proposalId The id of the proposal to vote on
* @param support The support value for the vote. 0=against, 1=for, 2=abstain
*/
function castVote(uint proposalId, uint8 support) external {
emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), "");
}
/**
* @notice Cast a vote for a proposal with a reason
* @param proposalId The id of the proposal to vote on
* @param support The support value for the vote. 0=against, 1=for, 2=abstain
* @param reason The reason given for the vote by the voter
*/
function castVoteWithReason(uint proposalId, uint8 support, string calldata reason) external {
emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), reason);
}
/**
* @notice Cast a vote for a proposal by signature
* @dev External function that accepts EIP-712 signatures for voting on proposals.
*/
function castVoteBySig(uint proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainIdInternal(), address(this)));
bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "GovernorBravo::castVoteBySig: invalid signature");
emit VoteCast(signatory, proposalId, support, castVoteInternal(signatory, proposalId, support), "");
}
/**
* @dev Allows batching to castVote function
*/
function castVotes(uint[] calldata proposalIds, uint8[] calldata supportVals) external {
require(proposalIds.length == supportVals.length, "count mismatch");
for (uint256 i = 0; i < proposalIds.length; i++) {
emit VoteCast(msg.sender, proposalIds[i], supportVals[i], castVoteInternal(msg.sender, proposalIds[i], supportVals[i]), "");
}
}
/**
* @dev Allows batching to castVoteWithReason function
*/
function castVotesWithReason(uint[] calldata proposalIds, uint8[] calldata supportVals, string[] calldata reasons) external {
require(proposalIds.length == supportVals.length && proposalIds.length == reasons.length, "count mismatch");
for (uint256 i = 0; i < proposalIds.length; i++) {
emit VoteCast(msg.sender, proposalIds[i], supportVals[i], castVoteInternal(msg.sender, proposalIds[i], supportVals[i]), reasons[i]);
}
}
/**
* @dev Allows batching to castVoteBySig function
*/
function castVotesBySig(uint[] calldata proposalIds, uint8[] calldata supportVals, uint8[] calldata vs, bytes32[] calldata rs, bytes32[] calldata ss) external {
require(proposalIds.length == supportVals.length && proposalIds.length == vs.length && proposalIds.length == rs.length && proposalIds.length == ss.length, "count mismatch");
for (uint256 i = 0; i < proposalIds.length; i++) {
castVoteBySig(proposalIds[i], supportVals[i], vs[i], rs[i], ss[i]);
}
}
/**
* @notice Internal function that caries out voting logic
* @param voter The voter that is casting their vote
* @param proposalId The id of the proposal to vote on
* @param support The support value for the vote. 0=against, 1=for, 2=abstain
* @return The number of votes cast
*/
function castVoteInternal(address voter, uint proposalId, uint8 support) internal returns (uint96) {
require(state(proposalId) == ProposalState.Active, "GovernorBravo::castVoteInternal: voting is closed");
require(support <= 2, "GovernorBravo::castVoteInternal: invalid vote type");
Proposal storage proposal = proposals[proposalId];
Receipt storage receipt = proposal.receipts[voter];
require(receipt.hasVoted == false, "GovernorBravo::castVoteInternal: voter already voted");
// 2**96-1 is greater than total supply of bzrx 1.3b*1e18 thus guaranteeing it won't ever overflow
uint96 votes = uint96(staking.votingBalanceOf(voter, proposalId));
if (support == 0) {
proposal.againstVotes = add256(proposal.againstVotes, votes);
} else if (support == 1) {
proposal.forVotes = add256(proposal.forVotes, votes);
} else if (support == 2) {
proposal.abstainVotes = add256(proposal.abstainVotes, votes);
}
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = votes;
return votes;
}
/**
* @notice Admin function for setting the voting delay
* @param newVotingDelay new voting delay, in blocks
*/
function __setVotingDelay(uint newVotingDelay) external {
require(msg.sender == admin, "GovernorBravo::__setVotingDelay: admin only");
require(newVotingDelay >= MIN_VOTING_DELAY && newVotingDelay <= MAX_VOTING_DELAY, "GovernorBravo::__setVotingDelay: invalid voting delay");
uint oldVotingDelay = votingDelay;
votingDelay = newVotingDelay;
emit VotingDelaySet(oldVotingDelay,votingDelay);
}
/**
* @notice Admin function for setting the voting period
* @param newVotingPeriod new voting period, in blocks
*/
function __setVotingPeriod(uint newVotingPeriod) external {
require(msg.sender == admin, "GovernorBravo::__setVotingPeriod: admin only");
require(newVotingPeriod >= MIN_VOTING_PERIOD && newVotingPeriod <= MAX_VOTING_PERIOD, "GovernorBravo::__setVotingPeriod: invalid voting period");
uint oldVotingPeriod = votingPeriod;
votingPeriod = newVotingPeriod;
emit VotingPeriodSet(oldVotingPeriod, votingPeriod);
}
/**
* @notice Admin function for setting the proposal threshold
* @dev newProposalThreshold must be greater than the hardcoded min
* @param newProposalThreshold new proposal threshold
*/
function __setProposalThreshold(uint newProposalThreshold) external {
require(msg.sender == admin, "GovernorBravo::__setProposalThreshold: admin only");
require(newProposalThreshold >= MIN_PROPOSAL_THRESHOLD && newProposalThreshold <= MAX_PROPOSAL_THRESHOLD, "GovernorBravo::__setProposalThreshold: invalid proposal threshold");
uint oldProposalThreshold = proposalThreshold;
proposalThreshold = newProposalThreshold;
emit ProposalThresholdSet(oldProposalThreshold, proposalThreshold);
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `__acceptLocalAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `__acceptLocalAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
*/
function __setPendingLocalAdmin(address newPendingAdmin) external {
// Check caller = admin
require(msg.sender == admin, "GovernorBravo:__setPendingLocalAdmin: admin only");
// 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 __acceptLocalAdmin() external {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
require(msg.sender == pendingAdmin && msg.sender != address(0), "GovernorBravo:__acceptLocalAdmin: pending admin only");
// 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);
}
function __changeGuardian(address guardian_) public {
require(msg.sender == guardian, "GovernorBravo::__changeGuardian: sender must be gov guardian");
require(guardian_ != address(0), "GovernorBravo::__changeGuardian: not allowed");
guardian = guardian_;
}
function __acceptAdmin() public {
require(msg.sender == guardian, "GovernorBravo::__acceptAdmin: sender must be gov guardian");
timelock.acceptAdmin();
}
function __abdicate() public {
require(msg.sender == guardian, "GovernorBravo::__abdicate: sender must be gov guardian");
guardian = address(0);
}
function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public {
require(msg.sender == guardian, "GovernorBravo::__queueSetTimelockPendingAdmin: sender must be gov guardian");
timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public {
require(msg.sender == guardian, "GovernorBravo::__executeSetTimelockPendingAdmin: sender must be gov guardian");
timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
function add256(uint256 a, uint256 b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "addition overflow");
return c;
}
function sub256(uint256 a, uint256 b) internal pure returns (uint) {
require(b <= a, "subtraction underflow");
return a - b;
}
function getChainIdInternal() internal pure returns (uint) {
uint chainId;
assembly { chainId := chainid() }
return chainId;
}
}
contract StakingVoteDelegatorState is StakingUpgradeable {
// 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 StakingVoteDelegatorConstants {
address constant internal ZERO_ADDRESS = address(0);
IStaking constant staking = IStaking(0xe95Ebce2B02Ee07dEF5Ed6B53289801F7Fc137A4);
/// @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);
}
contract StakingVoteDelegator is StakingVoteDelegatorState, StakingVoteDelegatorConstants {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* @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 {
if(delegatee == ZERO_ADDRESS){
delegatee = msg.sender;
}
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("STAKING")),
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), "Staking::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Staking::delegateBySig: invalid nonce");
require(now <= expiry, "Staking::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) public view returns (uint256) {
require(blockNumber < block.number, "Staking::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 = staking.votingFromStakedBalanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function moveDelegates(address srcRep, address dstRep, uint256 amount) public {
require(msg.sender == address(staking), "unauthorized");
_moveDelegates(srcRep, dstRep, amount);
}
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 > srcRepOld)? srcRepOld : 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, "Staking::_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 StakingV1_1 is StakingState, StakingConstants, PausableGuardian {
using MathUtil for uint256;
modifier onlyEOA() {
require(msg.sender == tx.origin, "unauthorized");
_;
}
function getCurrentFeeTokens()
external
view
returns (address[] memory)
{
return currentFeeTokens;
}
function _pendingSushiRewards(address _user)
internal
view
returns (uint256)
{
uint256 pendingSushi = IMasterChefSushi(SUSHI_MASTERCHEF)
.pendingSushi(BZRX_ETH_SUSHI_MASTERCHEF_PID, address(this));
uint256 totalSupply = _totalSupplyPerToken[LPToken];
return _pendingAltRewards(
SUSHI,
_user,
balanceOfByAsset(LPToken, _user),
totalSupply != 0 ? pendingSushi.mul(1e12).div(totalSupply) : 0
);
}
function pendingCrvRewards(address account) external returns(uint256){
(uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting) = _earned(
account,
bzrxPerTokenStored,
stableCoinPerTokenStored
);
(,stableCoinRewardsEarned) = _syncVesting(
account,
bzrxRewardsEarned,
stableCoinRewardsEarned,
bzrxRewardsVesting,
stableCoinRewardsVesting
);
return _pendingCrvRewards(account, stableCoinRewardsEarned);
}
function _pendingCrvRewards(address _user, uint256 stableCoinRewardsEarned)
internal
returns (uint256)
{
uint256 totalSupply = curve3PoolGauge.balanceOf(address(this));
uint256 pendingCrv = curve3PoolGauge.claimable_tokens(address(this));
return _pendingAltRewards(
CRV,
_user,
stableCoinRewardsEarned,
(totalSupply != 0) ? pendingCrv.mul(1e12).div(totalSupply) : 0
);
}
function _pendingAltRewards(address token, address _user, uint256 userSupply, uint256 extraRewardsPerShare)
internal
view
returns (uint256)
{
uint256 _altRewardsPerShare = altRewardsPerShare[token].add(extraRewardsPerShare);
if (_altRewardsPerShare == 0)
return 0;
IStaking.AltRewardsUserInfo memory altRewardsUserInfo = userAltRewardsPerShare[_user][token];
return altRewardsUserInfo.pendingRewards.add(
(_altRewardsPerShare.sub(altRewardsUserInfo.rewardsPerShare)).mul(userSupply).div(1e12)
);
}
function _depositToSushiMasterchef(uint256 amount)
internal
{
uint256 sushiBalanceBefore = IERC20(SUSHI).balanceOf(address(this));
IMasterChefSushi(SUSHI_MASTERCHEF).deposit(
BZRX_ETH_SUSHI_MASTERCHEF_PID,
amount
);
uint256 sushiRewards = IERC20(SUSHI).balanceOf(address(this)) - sushiBalanceBefore;
if (sushiRewards != 0) {
_addAltRewards(SUSHI, sushiRewards);
}
}
function _withdrawFromSushiMasterchef(uint256 amount)
internal
{
uint256 sushiBalanceBefore = IERC20(SUSHI).balanceOf(address(this));
IMasterChefSushi(SUSHI_MASTERCHEF).withdraw(
BZRX_ETH_SUSHI_MASTERCHEF_PID,
amount
);
uint256 sushiRewards = IERC20(SUSHI).balanceOf(address(this)) - sushiBalanceBefore;
if (sushiRewards != 0) {
_addAltRewards(SUSHI, sushiRewards);
}
}
function _depositTo3Pool(
uint256 amount)
internal
{
if(amount == 0)
curve3PoolGauge.deposit(curve3Crv.balanceOf(address(this)));
// Trigger claim rewards from curve pool
uint256 crvBalanceBefore = IERC20(CRV).balanceOf(address(this));
curveMinter.mint(address(curve3PoolGauge));
uint256 crvBalanceAfter = IERC20(CRV).balanceOf(address(this)) - crvBalanceBefore;
if(crvBalanceAfter != 0){
_addAltRewards(CRV, crvBalanceAfter);
}
}
function _withdrawFrom3Pool(uint256 amount)
internal
{
if(amount != 0)
curve3PoolGauge.withdraw(amount);
//Trigger claim rewards from curve pool
uint256 crvBalanceBefore = IERC20(CRV).balanceOf(address(this));
curveMinter.mint(address(curve3PoolGauge));
uint256 crvBalanceAfter = IERC20(CRV).balanceOf(address(this)) - crvBalanceBefore;
if(crvBalanceAfter != 0){
_addAltRewards(CRV, crvBalanceAfter);
}
}
function stake(
address[] memory tokens,
uint256[] memory values
)
public
pausable
updateRewards(msg.sender)
{
require(tokens.length == values.length, "count mismatch");
StakingVoteDelegator _voteDelegator = StakingVoteDelegator(voteDelegator);
address currentDelegate = _voteDelegator.delegates(msg.sender);
ProposalState memory _proposalState = _getProposalState();
uint256 votingBalanceBefore = _votingFromStakedBalanceOf(msg.sender, _proposalState, true);
for (uint256 i = 0; i < tokens.length; i++) {
address token = tokens[i];
require(token == BZRX || token == vBZRX || token == iBZRX || token == LPToken, "invalid token");
uint256 stakeAmount = values[i];
if (stakeAmount == 0) {
continue;
}
uint256 pendingBefore = (token == LPToken) ? _pendingSushiRewards(msg.sender) : 0;
_balancesPerToken[token][msg.sender] = _balancesPerToken[token][msg.sender].add(stakeAmount);
_totalSupplyPerToken[token] = _totalSupplyPerToken[token].add(stakeAmount);
IERC20(token).safeTransferFrom(msg.sender, address(this), stakeAmount);
// Deposit to sushi masterchef
if (token == LPToken) {
_depositToSushiMasterchef(
IERC20(LPToken).balanceOf(address(this))
);
userAltRewardsPerShare[msg.sender][SUSHI] = IStaking.AltRewardsUserInfo({
rewardsPerShare: altRewardsPerShare[SUSHI],
pendingRewards: pendingBefore
}
);
}
emit Stake(
msg.sender,
token,
currentDelegate,
stakeAmount
);
}
_voteDelegator.moveDelegates(ZERO_ADDRESS, currentDelegate, _votingFromStakedBalanceOf(msg.sender, _proposalState, true).sub(votingBalanceBefore));
}
function unstake(
address[] memory tokens,
uint256[] memory values
)
public
pausable
updateRewards(msg.sender)
{
require(tokens.length == values.length, "count mismatch");
StakingVoteDelegator _voteDelegator = StakingVoteDelegator(voteDelegator);
address currentDelegate = _voteDelegator.delegates(msg.sender);
ProposalState memory _proposalState = _getProposalState();
uint256 votingBalanceBefore = _votingFromStakedBalanceOf(msg.sender, _proposalState, true);
for (uint256 i = 0; i < tokens.length; i++) {
address token = tokens[i];
require(token == BZRX || token == vBZRX || token == iBZRX || token == LPToken || token == LPTokenOld, "invalid token");
uint256 unstakeAmount = values[i];
uint256 stakedAmount = _balancesPerToken[token][msg.sender];
if (unstakeAmount == 0 || stakedAmount == 0) {
continue;
}
if (unstakeAmount > stakedAmount) {
unstakeAmount = stakedAmount;
}
uint256 pendingBefore = (token == LPToken) ? _pendingSushiRewards(msg.sender) : 0;
_balancesPerToken[token][msg.sender] = stakedAmount - unstakeAmount; // will not overflow
_totalSupplyPerToken[token] = _totalSupplyPerToken[token] - unstakeAmount; // will not overflow
if (token == BZRX && IERC20(BZRX).balanceOf(address(this)) < unstakeAmount) {
// settle vested BZRX only if needed
IVestingToken(vBZRX).claim();
}
// Withdraw to sushi masterchef
if (token == LPToken) {
_withdrawFromSushiMasterchef(unstakeAmount);
userAltRewardsPerShare[msg.sender][SUSHI] = IStaking.AltRewardsUserInfo({
rewardsPerShare: altRewardsPerShare[SUSHI],
pendingRewards: pendingBefore
}
);
}
IERC20(token).safeTransfer(msg.sender, unstakeAmount);
emit Unstake(
msg.sender,
token,
currentDelegate,
unstakeAmount
);
}
_voteDelegator.moveDelegates(currentDelegate, ZERO_ADDRESS, votingBalanceBefore.sub(_votingFromStakedBalanceOf(msg.sender, _proposalState, true)));
}
function claim(
bool restake)
external
pausable
updateRewards(msg.sender)
returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned)
{
return _claim(restake);
}
function claimAltRewards()
external
pausable
returns (uint256 sushiRewardsEarned, uint256 crvRewardsEarned)
{
sushiRewardsEarned = _claimSushi();
crvRewardsEarned = _claimCrv();
if(sushiRewardsEarned != 0){
emit ClaimAltRewards(msg.sender, SUSHI, sushiRewardsEarned);
}
if(crvRewardsEarned != 0){
emit ClaimAltRewards(msg.sender, CRV, crvRewardsEarned);
}
}
function claimBzrx()
external
pausable
updateRewards(msg.sender)
returns (uint256 bzrxRewardsEarned)
{
bzrxRewardsEarned = _claimBzrx(false);
emit Claim(
msg.sender,
bzrxRewardsEarned,
0
);
}
function claim3Crv()
external
pausable
updateRewards(msg.sender)
returns (uint256 stableCoinRewardsEarned)
{
stableCoinRewardsEarned = _claim3Crv();
emit Claim(
msg.sender,
0,
stableCoinRewardsEarned
);
}
function claimSushi()
external
pausable
returns (uint256 sushiRewardsEarned)
{
sushiRewardsEarned = _claimSushi();
if(sushiRewardsEarned != 0){
emit ClaimAltRewards(msg.sender, SUSHI, sushiRewardsEarned);
}
}
function claimCrv()
external
pausable
returns (uint256 crvRewardsEarned)
{
crvRewardsEarned = _claimCrv();
if(crvRewardsEarned != 0){
emit ClaimAltRewards(msg.sender, CRV, crvRewardsEarned);
}
}
function _claim(
bool restake)
internal
returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned)
{
bzrxRewardsEarned = _claimBzrx(restake);
stableCoinRewardsEarned = _claim3Crv();
emit Claim(
msg.sender,
bzrxRewardsEarned,
stableCoinRewardsEarned
);
}
function _claimBzrx(
bool restake)
internal
returns (uint256 bzrxRewardsEarned)
{
bzrxRewardsEarned = bzrxRewards[msg.sender];
if (bzrxRewardsEarned != 0) {
bzrxRewards[msg.sender] = 0;
if (restake) {
_restakeBZRX(
msg.sender,
bzrxRewardsEarned
);
} else {
if (IERC20(BZRX).balanceOf(address(this)) < bzrxRewardsEarned) {
// settle vested BZRX only if needed
IVestingToken(vBZRX).claim();
}
IERC20(BZRX).transfer(msg.sender, bzrxRewardsEarned);
}
}
}
function _claim3Crv()
internal
returns (uint256 stableCoinRewardsEarned)
{
stableCoinRewardsEarned = stableCoinRewards[msg.sender];
if (stableCoinRewardsEarned != 0) {
uint256 pendingCrv = _pendingCrvRewards(msg.sender, stableCoinRewardsEarned);
uint256 curve3CrvBalance = curve3Crv.balanceOf(address(this));
_withdrawFrom3Pool(stableCoinRewardsEarned);
userAltRewardsPerShare[msg.sender][CRV] = IStaking.AltRewardsUserInfo({
rewardsPerShare: altRewardsPerShare[CRV],
pendingRewards: pendingCrv
}
);
stableCoinRewards[msg.sender] = 0;
curve3Crv.transfer(msg.sender, stableCoinRewardsEarned);
}
}
function _claimSushi()
internal
returns (uint256)
{
address _user = msg.sender;
uint256 lptUserSupply = balanceOfByAsset(LPToken, _user);
//This will trigger claim rewards from sushi masterchef
_depositToSushiMasterchef(
IERC20(LPToken).balanceOf(address(this))
);
uint256 pendingSushi = _pendingAltRewards(SUSHI, _user, lptUserSupply, 0);
userAltRewardsPerShare[_user][SUSHI] = IStaking.AltRewardsUserInfo({
rewardsPerShare: altRewardsPerShare[SUSHI],
pendingRewards: 0
}
);
if (pendingSushi != 0) {
IERC20(SUSHI).safeTransfer(_user, pendingSushi);
}
return pendingSushi;
}
function _claimCrv()
internal
returns (uint256)
{
address _user = msg.sender;
_depositTo3Pool(0);
(,uint256 stableCoinRewardsEarned,,) = _earned(_user, bzrxPerTokenStored, stableCoinPerTokenStored);
uint256 pendingCrv = _pendingCrvRewards(_user, stableCoinRewardsEarned);
userAltRewardsPerShare[_user][CRV] = IStaking.AltRewardsUserInfo({
rewardsPerShare: altRewardsPerShare[CRV],
pendingRewards: 0
}
);
if (pendingCrv != 0) {
IERC20(CRV).safeTransfer(_user, pendingCrv);
}
return pendingCrv;
}
function _restakeBZRX(
address account,
uint256 amount)
internal
{
StakingVoteDelegator _voteDelegator = StakingVoteDelegator(voteDelegator);
address currentDelegate = _voteDelegator.delegates(msg.sender);
ProposalState memory _proposalState = _getProposalState();
uint256 votingBalanceBefore = _votingFromStakedBalanceOf(msg.sender, _proposalState, true);
_balancesPerToken[BZRX][account] = _balancesPerToken[BZRX][account]
.add(amount);
_totalSupplyPerToken[BZRX] = _totalSupplyPerToken[BZRX]
.add(amount);
emit Stake(
account,
BZRX,
currentDelegate,
amount
);
_voteDelegator.moveDelegates(ZERO_ADDRESS, currentDelegate, _votingFromStakedBalanceOf(msg.sender, _proposalState, true).sub(votingBalanceBefore));
}
function exit()
public
// unstake() does check pausable
{
address[] memory tokens = new address[](4);
uint256[] memory values = new uint256[](4);
tokens[0] = iBZRX;
tokens[1] = LPToken;
tokens[2] = vBZRX;
tokens[3] = BZRX;
values[0] = uint256(-1);
values[1] = uint256(-1);
values[2] = uint256(-1);
values[3] = uint256(-1);
unstake(tokens, values); // calls updateRewards
_claim(false);
}
modifier updateRewards(address account) {
uint256 _bzrxPerTokenStored = bzrxPerTokenStored;
uint256 _stableCoinPerTokenStored = stableCoinPerTokenStored;
(uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting) = _earned(
account,
_bzrxPerTokenStored,
_stableCoinPerTokenStored
);
bzrxRewardsPerTokenPaid[account] = _bzrxPerTokenStored;
stableCoinRewardsPerTokenPaid[account] = _stableCoinPerTokenStored;
// vesting amounts get updated before sync
bzrxVesting[account] = bzrxRewardsVesting;
stableCoinVesting[account] = stableCoinRewardsVesting;
(bzrxRewards[account], stableCoinRewards[account]) = _syncVesting(
account,
bzrxRewardsEarned,
stableCoinRewardsEarned,
bzrxRewardsVesting,
stableCoinRewardsVesting
);
vestingLastSync[account] = block.timestamp;
_;
}
function earned(
address account)
external
view
returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting,
uint256 stableCoinRewardsVesting, uint256 sushiRewardsEarned)
{
(bzrxRewardsEarned, stableCoinRewardsEarned, bzrxRewardsVesting, stableCoinRewardsVesting) = _earned(
account,
bzrxPerTokenStored,
stableCoinPerTokenStored
);
(bzrxRewardsEarned, stableCoinRewardsEarned) = _syncVesting(
account,
bzrxRewardsEarned,
stableCoinRewardsEarned,
bzrxRewardsVesting,
stableCoinRewardsVesting
);
// discount vesting amounts for vesting time
uint256 multiplier = vestedBalanceForAmount(
1e36,
0,
block.timestamp
);
bzrxRewardsVesting = bzrxRewardsVesting
.sub(bzrxRewardsVesting
.mul(multiplier)
.div(1e36)
);
stableCoinRewardsVesting = stableCoinRewardsVesting
.sub(stableCoinRewardsVesting
.mul(multiplier)
.div(1e36)
);
uint256 pendingSushi = IMasterChefSushi(SUSHI_MASTERCHEF)
.pendingSushi(BZRX_ETH_SUSHI_MASTERCHEF_PID, address(this));
sushiRewardsEarned = _pendingAltRewards(
SUSHI,
account,
balanceOfByAsset(LPToken, account),
(_totalSupplyPerToken[LPToken] != 0) ? pendingSushi.mul(1e12).div(_totalSupplyPerToken[LPToken]) : 0
);
}
function _earned(
address account,
uint256 _bzrxPerToken,
uint256 _stableCoinPerToken)
internal
view
returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting)
{
uint256 bzrxPerTokenUnpaid = _bzrxPerToken.sub(bzrxRewardsPerTokenPaid[account]);
uint256 stableCoinPerTokenUnpaid = _stableCoinPerToken.sub(stableCoinRewardsPerTokenPaid[account]);
bzrxRewardsEarned = bzrxRewards[account];
stableCoinRewardsEarned = stableCoinRewards[account];
bzrxRewardsVesting = bzrxVesting[account];
stableCoinRewardsVesting = stableCoinVesting[account];
if (bzrxPerTokenUnpaid != 0 || stableCoinPerTokenUnpaid != 0) {
uint256 value;
uint256 multiplier;
uint256 lastSync;
(uint256 vestedBalance, uint256 vestingBalance) = balanceOfStored(account);
value = vestedBalance
.mul(bzrxPerTokenUnpaid);
value /= 1e36;
bzrxRewardsEarned = value
.add(bzrxRewardsEarned);
value = vestedBalance
.mul(stableCoinPerTokenUnpaid);
value /= 1e36;
stableCoinRewardsEarned = value
.add(stableCoinRewardsEarned);
if (vestingBalance != 0 && bzrxPerTokenUnpaid != 0) {
// add new vesting amount for BZRX
value = vestingBalance
.mul(bzrxPerTokenUnpaid);
value /= 1e36;
bzrxRewardsVesting = bzrxRewardsVesting
.add(value);
// true up earned amount to vBZRX vesting schedule
lastSync = vestingLastSync[account];
multiplier = vestedBalanceForAmount(
1e36,
0,
lastSync
);
value = value
.mul(multiplier);
value /= 1e36;
bzrxRewardsEarned = bzrxRewardsEarned
.add(value);
}
if (vestingBalance != 0 && stableCoinPerTokenUnpaid != 0) {
// add new vesting amount for 3crv
value = vestingBalance
.mul(stableCoinPerTokenUnpaid);
value /= 1e36;
stableCoinRewardsVesting = stableCoinRewardsVesting
.add(value);
// true up earned amount to vBZRX vesting schedule
if (lastSync == 0) {
lastSync = vestingLastSync[account];
multiplier = vestedBalanceForAmount(
1e36,
0,
lastSync
);
}
value = value
.mul(multiplier);
value /= 1e36;
stableCoinRewardsEarned = stableCoinRewardsEarned
.add(value);
}
}
}
function _syncVesting(
address account,
uint256 bzrxRewardsEarned,
uint256 stableCoinRewardsEarned,
uint256 bzrxRewardsVesting,
uint256 stableCoinRewardsVesting)
internal
view
returns (uint256, uint256)
{
uint256 lastVestingSync = vestingLastSync[account];
if (lastVestingSync != block.timestamp) {
uint256 rewardsVested;
uint256 multiplier = vestedBalanceForAmount(
1e36,
lastVestingSync,
block.timestamp
);
if (bzrxRewardsVesting != 0) {
rewardsVested = bzrxRewardsVesting
.mul(multiplier)
.div(1e36);
bzrxRewardsEarned += rewardsVested;
}
if (stableCoinRewardsVesting != 0) {
rewardsVested = stableCoinRewardsVesting
.mul(multiplier)
.div(1e36);
stableCoinRewardsEarned += rewardsVested;
}
uint256 vBZRXBalance = _balancesPerToken[vBZRX][account];
if (vBZRXBalance != 0) {
// add vested BZRX to rewards balance
rewardsVested = vBZRXBalance
.mul(multiplier)
.div(1e36);
bzrxRewardsEarned += rewardsVested;
}
}
return (bzrxRewardsEarned, stableCoinRewardsEarned);
}
// note: anyone can contribute rewards to the contract
function addDirectRewards(
address[] calldata accounts,
uint256[] calldata bzrxAmounts,
uint256[] calldata stableCoinAmounts)
external
pausable
returns (uint256 bzrxTotal, uint256 stableCoinTotal)
{
require(accounts.length == bzrxAmounts.length && accounts.length == stableCoinAmounts.length, "count mismatch");
for (uint256 i = 0; i < accounts.length; i++) {
bzrxRewards[accounts[i]] = bzrxRewards[accounts[i]].add(bzrxAmounts[i]);
bzrxTotal = bzrxTotal.add(bzrxAmounts[i]);
stableCoinRewards[accounts[i]] = stableCoinRewards[accounts[i]].add(stableCoinAmounts[i]);
stableCoinTotal = stableCoinTotal.add(stableCoinAmounts[i]);
}
if (bzrxTotal != 0) {
IERC20(BZRX).transferFrom(msg.sender, address(this), bzrxTotal);
}
if (stableCoinTotal != 0) {
curve3Crv.transferFrom(msg.sender, address(this), stableCoinTotal);
_depositTo3Pool(stableCoinTotal);
}
}
// note: anyone can contribute rewards to the contract
function addRewards(
uint256 newBZRX,
uint256 newStableCoin)
external
pausable
{
if (newBZRX != 0 || newStableCoin != 0) {
_addRewards(newBZRX, newStableCoin);
if (newBZRX != 0) {
IERC20(BZRX).transferFrom(msg.sender, address(this), newBZRX);
}
if (newStableCoin != 0) {
curve3Crv.transferFrom(msg.sender, address(this), newStableCoin);
_depositTo3Pool(newStableCoin);
}
}
}
function _addRewards(
uint256 newBZRX,
uint256 newStableCoin)
internal
{
(vBZRXWeightStored, iBZRXWeightStored, LPTokenWeightStored) = getVariableWeights();
uint256 totalTokens = totalSupplyStored();
require(totalTokens != 0, "nothing staked");
bzrxPerTokenStored = newBZRX
.mul(1e36)
.div(totalTokens)
.add(bzrxPerTokenStored);
stableCoinPerTokenStored = newStableCoin
.mul(1e36)
.div(totalTokens)
.add(stableCoinPerTokenStored);
lastRewardsAddTime = block.timestamp;
emit AddRewards(
msg.sender,
newBZRX,
newStableCoin
);
}
function addAltRewards(address token, uint256 amount) public {
if (amount != 0) {
_addAltRewards(token, amount);
IERC20(token).transferFrom(msg.sender, address(this), amount);
}
}
function _addAltRewards(address token, uint256 amount) internal {
address poolAddress = token == SUSHI ? LPToken : token;
uint256 totalSupply = (token == CRV) ? curve3PoolGauge.balanceOf(address(this)) :_totalSupplyPerToken[poolAddress];
require(totalSupply != 0, "no deposits");
altRewardsPerShare[token] = altRewardsPerShare[token]
.add(amount.mul(1e12).div(totalSupply));
emit AddAltRewards(msg.sender, token, amount);
}
function getVariableWeights()
public
view
returns (uint256 vBZRXWeight, uint256 iBZRXWeight, uint256 LPTokenWeight)
{
uint256 totalVested = vestedBalanceForAmount(
_startingVBZRXBalance,
0,
block.timestamp
);
vBZRXWeight = SafeMath.mul(_startingVBZRXBalance - totalVested, 1e18) // overflow not possible
.div(_startingVBZRXBalance);
iBZRXWeight = _calcIBZRXWeight();
uint256 lpTokenSupply = _totalSupplyPerToken[LPToken];
if (lpTokenSupply != 0) {
// staked LP tokens are assumed to represent the total unstaked supply (circulated supply - staked BZRX)
uint256 normalizedLPTokenSupply = initialCirculatingSupply +
totalVested -
_totalSupplyPerToken[BZRX];
LPTokenWeight = normalizedLPTokenSupply
.mul(1e18)
.div(lpTokenSupply);
}
}
function _calcIBZRXWeight()
internal
view
returns (uint256)
{
return IERC20(BZRX).balanceOf(iBZRX)
.mul(1e50)
.div(IERC20(iBZRX).totalSupply());
}
function balanceOfByAsset(
address token,
address account)
public
view
returns (uint256 balance)
{
balance = _balancesPerToken[token][account];
}
function balanceOfByAssets(
address account)
external
view
returns (
uint256 bzrxBalance,
uint256 iBZRXBalance,
uint256 vBZRXBalance,
uint256 LPTokenBalance,
uint256 LPTokenBalanceOld
)
{
return (
balanceOfByAsset(BZRX, account),
balanceOfByAsset(iBZRX, account),
balanceOfByAsset(vBZRX, account),
balanceOfByAsset(LPToken, account),
balanceOfByAsset(LPTokenOld, account)
);
}
function balanceOfStored(
address account)
public
view
returns (uint256 vestedBalance, uint256 vestingBalance)
{
uint256 balance = _balancesPerToken[vBZRX][account];
if (balance != 0) {
vestingBalance = balance
.mul(vBZRXWeightStored)
.div(1e18);
}
vestedBalance = _balancesPerToken[BZRX][account];
balance = _balancesPerToken[iBZRX][account];
if (balance != 0) {
vestedBalance = balance
.mul(iBZRXWeightStored)
.div(1e50)
.add(vestedBalance);
}
balance = _balancesPerToken[LPToken][account];
if (balance != 0) {
vestedBalance = balance
.mul(LPTokenWeightStored)
.div(1e18)
.add(vestedBalance);
}
}
function totalSupplyByAsset(
address token)
external
view
returns (uint256)
{
return _totalSupplyPerToken[token];
}
function totalSupplyStored()
public
view
returns (uint256 supply)
{
supply = _totalSupplyPerToken[vBZRX]
.mul(vBZRXWeightStored)
.div(1e18);
supply = _totalSupplyPerToken[BZRX]
.add(supply);
supply = _totalSupplyPerToken[iBZRX]
.mul(iBZRXWeightStored)
.div(1e50)
.add(supply);
supply = _totalSupplyPerToken[LPToken]
.mul(LPTokenWeightStored)
.div(1e18)
.add(supply);
}
function vestedBalanceForAmount(
uint256 tokenBalance,
uint256 lastUpdate,
uint256 vestingEndTime)
public
view
returns (uint256 vested)
{
vestingEndTime = vestingEndTime.min256(block.timestamp);
if (vestingEndTime > lastUpdate) {
if (vestingEndTime <= vestingCliffTimestamp ||
lastUpdate >= vestingEndTimestamp) {
// time cannot be before vesting starts
// OR all vested token has already been claimed
return 0;
}
if (lastUpdate < vestingCliffTimestamp) {
// vesting starts at the cliff timestamp
lastUpdate = vestingCliffTimestamp;
}
if (vestingEndTime > vestingEndTimestamp) {
// vesting ends at the end timestamp
vestingEndTime = vestingEndTimestamp;
}
uint256 timeSinceClaim = vestingEndTime.sub(lastUpdate);
vested = tokenBalance.mul(timeSinceClaim) / vestingDurationAfterCliff; // will never divide by 0
}
}
function votingFromStakedBalanceOf(
address account)
external
view
returns (uint256 totalVotes)
{
return _votingFromStakedBalanceOf(account, _getProposalState(), true);
}
function votingBalanceOf(
address account,
uint256 proposalId)
external
view
returns (uint256 totalVotes)
{
(,,,uint256 startBlock,,,,,,) = GovernorBravoDelegateStorageV1(governor).proposals(proposalId);
if (startBlock == 0) return 0;
return _votingBalanceOf(account, _proposalState[proposalId], startBlock - 1);
}
function votingBalanceOfNow(
address account)
external
view
returns (uint256 totalVotes)
{
return _votingBalanceOf(account, _getProposalState(), block.number - 1);
}
function _setProposalVals(
address account,
uint256 proposalId)
public
returns (uint256)
{
require(msg.sender == governor, "unauthorized");
require(_proposalState[proposalId].proposalTime == 0, "proposal exists");
ProposalState memory newProposal = _getProposalState();
_proposalState[proposalId] = newProposal;
return _votingBalanceOf(account, newProposal, block.number - 1);
}
function _getProposalState()
internal
view
returns (ProposalState memory)
{
return ProposalState({
proposalTime: block.timestamp - 1,
iBZRXWeight: _calcIBZRXWeight(),
lpBZRXBalance: 0, // IERC20(BZRX).balanceOf(LPToken),
lpTotalSupply: 0 //IERC20(LPToken).totalSupply()
});
}
// Voting balance not including delegated votes
function _votingFromStakedBalanceOf(
address account,
ProposalState memory proposal,
bool skipVestingLastSyncCheck)
internal
view
returns (uint256 totalVotes)
{
uint256 _vestingLastSync = vestingLastSync[account];
if (proposal.proposalTime == 0 || (!skipVestingLastSyncCheck && _vestingLastSync > proposal.proposalTime - 1)) {
return 0;
}
// user is attributed a staked balance of vested BZRX, from their last update to the present
totalVotes = vestedBalanceForAmount(
_balancesPerToken[vBZRX][account],
_vestingLastSync,
proposal.proposalTime
);
totalVotes = _balancesPerToken[BZRX][account]
.add(bzrxRewards[account]) // unclaimed BZRX rewards count as votes
.add(totalVotes);
totalVotes = _balancesPerToken[iBZRX][account]
.mul(proposal.iBZRXWeight)
.div(1e50)
.add(totalVotes);
}
// Voting balance including delegated votes
function _votingBalanceOf(
address account,
ProposalState memory proposal,
uint blocknumber)
internal
view
returns (uint256 totalVotes)
{
StakingVoteDelegator _voteDelegator = StakingVoteDelegator(voteDelegator);
address _delegate = _voteDelegator.delegates(account);
if(_delegate == ZERO_ADDRESS) { // has not delegated yet
return _voteDelegator.getPriorVotes(account, blocknumber).add(_votingFromStakedBalanceOf(account, proposal, false));
}
return _voteDelegator.getPriorVotes(account, blocknumber);
}
// OnlyOwner functions
function updateSettings(
address settingsTarget,
bytes memory callData)
public
onlyOwner
returns(bytes memory)
{
(bool result,) = settingsTarget.delegatecall(callData);
assembly {
let size := returndatasize
let ptr := mload(0x40)
returndatacopy(ptr, 0, size)
if eq(result, 0) { revert(ptr, size) }
return(ptr, size)
}
}
} | Token => (User => Info) | mapping(address => mapping(address => IStaking.AltRewardsUserInfo)) public userAltRewardsPerShare;
| 260,264 | [
1,
1345,
516,
261,
1299,
516,
3807,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
467,
510,
6159,
18,
10655,
17631,
14727,
21015,
3719,
1071,
729,
10655,
17631,
14727,
2173,
9535,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0xa1C7345503A008a9FdF660393A3a8F9448c61f2A/sources/contracts/Vault.sol | @notice Emitted after perfomance fee updation. @param oldFee The old performance fee on vault. @param newFee The new performance fee on vault. | event UpdatePerformanceFee(uint256 oldFee, uint256 newFee);
| 3,153,960 | [
1,
1514,
11541,
1839,
14184,
362,
1359,
14036,
2166,
367,
18,
225,
1592,
14667,
1021,
1592,
9239,
14036,
603,
9229,
18,
225,
394,
14667,
1021,
394,
9239,
14036,
603,
9229,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
871,
2315,
25024,
14667,
12,
11890,
5034,
1592,
14667,
16,
2254,
5034,
394,
14667,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.16;
/**
* Math operations with safety checks
*/
contract SafeMath {
function safeMul(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) internal returns (uint256) {
assert(b > 0);
uint256 c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint256 a, uint256 b) internal returns (uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a + b;
assert(c>=a && c>=b);
return c;
}
}
contract EthPredict is SafeMath{
string public name;
string public symbol;
address public owner;
uint8 public decimals;
uint256 public totalSupply;
address public icoContractAddress;
uint256 public tokensTotalSupply = 1000 * (10**6) * 10**18;
mapping (address => bool) restrictedAddresses;
uint256 constant initialSupply = 100 * (10**6) * 10**18;
string constant tokenName = 'EthPredictToken';
uint8 constant decimalUnits = 18;
string constant tokenSymbol = 'EPT';
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => uint256) public freezeOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
/* This notifies clients about the amount frozen */
event Freeze(address indexed from, uint256 value);
/* This notifies clients about the amount unfrozen */
event Unfreeze(address indexed from, uint256 value);
// Mint event
event Mint(address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
modifier onlyOwner {
assert(owner == msg.sender);
_;
}
/* Initializes contract with initial supply tokens to the creator of the contract */
function EthPredict() {
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
totalSupply = initialSupply; // Update total supply
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
owner = msg.sender;
}
/* Send coins */
function transfer(address _to, uint256 _value) { // Prevent transfer to 0x0 address. Use burn() instead
require (_value > 0) ;
require (balanceOf[msg.sender] >= _value); // Check if the sender has enough
require (balanceOf[_to] + _value >= balanceOf[_to]) ; // Check for overflows
require (!restrictedAddresses[_to]);
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
}
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint256 _value)
returns (bool success) {
allowance[msg.sender][_spender] = _value; // Set allowance
Approval(msg.sender, _spender, _value); // Raise Approval event
return true;
}
function mintTokens(address _to, uint256 _amount) {
require (msg.sender == icoContractAddress); // Check if minter is ico Contract address;
require (_amount != 0 ) ; // Check if values are not null;
require (balanceOf[_to] + _amount > balanceOf[_to]) ;// Check for overflows
require (totalSupply <=tokensTotalSupply);
//require (!restrictedAddresses[_to]); //restrictedAddresse
totalSupply += _amount; // Update total supply
balanceOf[_to] += _amount; // Set minted coins to target
Mint(_to, _amount); // Create Mint event
Transfer(0x0, _to, _amount); // Create Transfer event from 0x
}
function prodTokens(address _to, uint256 _amount)
onlyOwner {
require (_amount != 0 ) ; // Check if values are not null;
require (balanceOf[_to] + _amount > balanceOf[_to]) ; // Check for overflows
require (totalSupply <=tokensTotalSupply);
//require (!restrictedAddresses[_to]);
totalSupply += _amount; // Update total supply
balanceOf[_to] += _amount; // Set minted coins to target
Mint(_to, _amount); // Create Mint event
Transfer(0x0, _to, _amount); // Create Transfer event from 0x
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to] + _value >= balanceOf[_to]) ; // Check for overflows
require (_value <= allowance[_from][msg.sender]) ; // Check allowance
require (!restrictedAddresses[_to]);
balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value);
Transfer(_from, _to, _value);
return true;
}
function burn(uint256 _value) returns (bool success) {
require (balanceOf[msg.sender] >= _value) ; // Check if the sender has enough
require (_value <= 0) ;
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
function freeze(uint256 _value) returns (bool success) {
require (balanceOf[msg.sender] >= _value) ; // Check if the sender has enough
require (_value > 0) ;
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value); // Updates totalSupply
Freeze(msg.sender, _value);
return true;
}
function unfreeze(uint256 _value) returns (bool success) {
require (balanceOf[msg.sender] >= _value) ; // Check if the sender has enough
require (_value > 0) ;
freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value); // Subtract from the sender
balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value);
Unfreeze(msg.sender, _value);
return true;
}
// transfer balance to owner
function withdrawEther(uint256 amount)
onlyOwner {
owner.transfer(amount);
}
function totalSupply() constant returns (uint256 Supply) {
return totalSupply;
}
/* Get balance of specific address */
function balanceOf(address _owner) constant returns (uint256 balance) {
return balanceOf[_owner];
}
// can accept ether
function() payable {
}
function changeICOAddress(address _newAddress) onlyOwner{
icoContractAddress = _newAddress;
}
/* Owner can add new restricted address or removes one */
function editRestrictedAddress(address _newRestrictedAddress) onlyOwner {
restrictedAddresses[_newRestrictedAddress] = !restrictedAddresses[_newRestrictedAddress];
}
function isRestrictedAddress(address _querryAddress) constant returns (bool answer){
return restrictedAddresses[_querryAddress];
}
} | Check if the sender has enough
| require (balanceOf[_from] >= _value); | 5,366,228 | [
1,
1564,
309,
326,
5793,
711,
7304,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2583,
261,
12296,
951,
63,
67,
2080,
65,
1545,
389,
1132,
1769,
5375,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
// Sources flattened with hardhat v2.6.7 https://hardhat.org
// File contracts/Math/SafeMath.sol
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File contracts/FXS/IFxs.sol
interface IFxs {
function DEFAULT_ADMIN_ROLE() external view returns(bytes32);
function FRAXStablecoinAdd() external view returns(address);
function FXS_DAO_min() external view returns(uint256);
function allowance(address owner, address spender) external view returns(uint256);
function approve(address spender, uint256 amount) external returns(bool);
function balanceOf(address account) external view returns(uint256);
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
function checkpoints(address, uint32) external view returns(uint32 fromBlock, uint96 votes);
function decimals() external view returns(uint8);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns(bool);
function genesis_supply() external view returns(uint256);
function getCurrentVotes(address account) external view returns(uint96);
function getPriorVotes(address account, uint256 blockNumber) external view returns(uint96);
function getRoleAdmin(bytes32 role) external view returns(bytes32);
function getRoleMember(bytes32 role, uint256 index) external view returns(address);
function getRoleMemberCount(bytes32 role) external view returns(uint256);
function grantRole(bytes32 role, address account) external;
function hasRole(bytes32 role, address account) external view returns(bool);
function increaseAllowance(address spender, uint256 addedValue) external returns(bool);
function mint(address to, uint256 amount) external;
function name() external view returns(string memory);
function numCheckpoints(address) external view returns(uint32);
function oracle_address() external view returns(address);
function owner_address() external view returns(address);
function pool_burn_from(address b_address, uint256 b_amount) external;
function pool_mint(address m_address, uint256 m_amount) external;
function renounceRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function setFRAXAddress(address frax_contract_address) external;
function setFXSMinDAO(uint256 min_FXS) external;
function setOracle(address new_oracle) external;
function setOwner(address _owner_address) external;
function setTimelock(address new_timelock) external;
function symbol() external view returns(string memory);
function timelock_address() external view returns(address);
function toggleVotes() external;
function totalSupply() external view returns(uint256);
function trackingVotes() external view returns(bool);
function transfer(address recipient, uint256 amount) external returns(bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns(bool);
}
// File contracts/Common/Context.sol
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return payable(msg.sender);
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File contracts/ERC20/IERC20.sol
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File contracts/Utils/Address.sol
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File contracts/ERC20/ERC20.sol
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory __name, string memory __symbol) public {
_name = __name;
_symbol = __symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.approve(address spender, uint256 amount)
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for `accounts`'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal virtual {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of `from`'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of `from`'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File contracts/Frax/IFrax.sol
interface IFrax {
function COLLATERAL_RATIO_PAUSER() external view returns (bytes32);
function DEFAULT_ADMIN_ADDRESS() external view returns (address);
function DEFAULT_ADMIN_ROLE() external view returns (bytes32);
function addPool(address pool_address ) external;
function allowance(address owner, address spender ) external view returns (uint256);
function approve(address spender, uint256 amount ) external returns (bool);
function balanceOf(address account ) external view returns (uint256);
function burn(uint256 amount ) external;
function burnFrom(address account, uint256 amount ) external;
function collateral_ratio_paused() external view returns (bool);
function controller_address() external view returns (address);
function creator_address() external view returns (address);
function decimals() external view returns (uint8);
function decreaseAllowance(address spender, uint256 subtractedValue ) external returns (bool);
function eth_usd_consumer_address() external view returns (address);
function eth_usd_price() external view returns (uint256);
function frax_eth_oracle_address() external view returns (address);
function frax_info() external view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256);
function frax_pools(address ) external view returns (bool);
function frax_pools_array(uint256 ) external view returns (address);
function frax_price() external view returns (uint256);
function frax_step() external view returns (uint256);
function fxs_address() external view returns (address);
function fxs_eth_oracle_address() external view returns (address);
function fxs_price() external view returns (uint256);
function genesis_supply() external view returns (uint256);
function getRoleAdmin(bytes32 role ) external view returns (bytes32);
function getRoleMember(bytes32 role, uint256 index ) external view returns (address);
function getRoleMemberCount(bytes32 role ) external view returns (uint256);
function globalCollateralValue() external view returns (uint256);
function global_collateral_ratio() external view returns (uint256);
function grantRole(bytes32 role, address account ) external;
function hasRole(bytes32 role, address account ) external view returns (bool);
function increaseAllowance(address spender, uint256 addedValue ) external returns (bool);
function last_call_time() external view returns (uint256);
function minting_fee() external view returns (uint256);
function name() external view returns (string memory);
function owner_address() external view returns (address);
function pool_burn_from(address b_address, uint256 b_amount ) external;
function pool_mint(address m_address, uint256 m_amount ) external;
function price_band() external view returns (uint256);
function price_target() external view returns (uint256);
function redemption_fee() external view returns (uint256);
function refreshCollateralRatio() external;
function refresh_cooldown() external view returns (uint256);
function removePool(address pool_address ) external;
function renounceRole(bytes32 role, address account ) external;
function revokeRole(bytes32 role, address account ) external;
function setController(address _controller_address ) external;
function setETHUSDOracle(address _eth_usd_consumer_address ) external;
function setFRAXEthOracle(address _frax_oracle_addr, address _weth_address ) external;
function setFXSAddress(address _fxs_address ) external;
function setFXSEthOracle(address _fxs_oracle_addr, address _weth_address ) external;
function setFraxStep(uint256 _new_step ) external;
function setMintingFee(uint256 min_fee ) external;
function setOwner(address _owner_address ) external;
function setPriceBand(uint256 _price_band ) external;
function setPriceTarget(uint256 _new_price_target ) external;
function setRedemptionFee(uint256 red_fee ) external;
function setRefreshCooldown(uint256 _new_cooldown ) external;
function setTimelock(address new_timelock ) external;
function symbol() external view returns (string memory);
function timelock_address() external view returns (address);
function toggleCollateralRatio() external;
function totalSupply() external view returns (uint256);
function transfer(address recipient, uint256 amount ) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount ) external returns (bool);
function weth_address() external view returns (address);
}
// File contracts/Frax/IFraxAMOMinter.sol
// MAY need to be updated
interface IFraxAMOMinter {
function FRAX() external view returns(address);
function FXS() external view returns(address);
function acceptOwnership() external;
function addAMO(address amo_address, bool sync_too) external;
function allAMOAddresses() external view returns(address[] memory);
function allAMOsLength() external view returns(uint256);
function amos(address) external view returns(bool);
function amos_array(uint256) external view returns(address);
function burnFraxFromAMO(uint256 frax_amount) external;
function burnFxsFromAMO(uint256 fxs_amount) external;
function col_idx() external view returns(uint256);
function collatDollarBalance() external view returns(uint256);
function collatDollarBalanceStored() external view returns(uint256);
function collat_borrow_cap() external view returns(int256);
function collat_borrowed_balances(address) external view returns(int256);
function collat_borrowed_sum() external view returns(int256);
function collateral_address() external view returns(address);
function collateral_token() external view returns(address);
function correction_offsets_amos(address, uint256) external view returns(int256);
function custodian_address() external view returns(address);
function dollarBalances() external view returns(uint256 frax_val_e18, uint256 collat_val_e18);
// function execute(address _to, uint256 _value, bytes _data) external returns(bool, bytes);
function fraxDollarBalanceStored() external view returns(uint256);
function fraxTrackedAMO(address amo_address) external view returns(int256);
function fraxTrackedGlobal() external view returns(int256);
function frax_mint_balances(address) external view returns(int256);
function frax_mint_cap() external view returns(int256);
function frax_mint_sum() external view returns(int256);
function fxs_mint_balances(address) external view returns(int256);
function fxs_mint_cap() external view returns(int256);
function fxs_mint_sum() external view returns(int256);
function giveCollatToAMO(address destination_amo, uint256 collat_amount) external;
function min_cr() external view returns(uint256);
function mintFraxForAMO(address destination_amo, uint256 frax_amount) external;
function mintFxsForAMO(address destination_amo, uint256 fxs_amount) external;
function missing_decimals() external view returns(uint256);
function nominateNewOwner(address _owner) external;
function nominatedOwner() external view returns(address);
function oldPoolCollectAndGive(address destination_amo) external;
function oldPoolRedeem(uint256 frax_amount) external;
function old_pool() external view returns(address);
function owner() external view returns(address);
function pool() external view returns(address);
function receiveCollatFromAMO(uint256 usdc_amount) external;
function recoverERC20(address tokenAddress, uint256 tokenAmount) external;
function removeAMO(address amo_address, bool sync_too) external;
function setAMOCorrectionOffsets(address amo_address, int256 frax_e18_correction, int256 collat_e18_correction) external;
function setCollatBorrowCap(uint256 _collat_borrow_cap) external;
function setCustodian(address _custodian_address) external;
function setFraxMintCap(uint256 _frax_mint_cap) external;
function setFraxPool(address _pool_address) external;
function setFxsMintCap(uint256 _fxs_mint_cap) external;
function setMinimumCollateralRatio(uint256 _min_cr) external;
function setTimelock(address new_timelock) external;
function syncDollarBalances() external;
function timelock_address() external view returns(address);
}
// File contracts/Uniswap/TransferHelper.sol
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// File contracts/Staking/Owned.sol
// https://docs.synthetix.io/contracts/Owned
contract Owned {
address public owner;
address public nominatedOwner;
constructor (address _owner) public {
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership() external {
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
require(msg.sender == owner, "Only the contract owner may perform this action");
_;
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
// File contracts/Oracle/AggregatorV3Interface.sol
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// File contracts/Frax/Pools/FraxPoolV3.sol
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ============================ FraxPoolV3 ============================
// ====================================================================
// Allows multiple stablecoins (fixed amount at initialization) as collateral
// LUSD, sUSD, USDP, Wrapped UST, and FEI initially
// For this pool, the goal is to accept crypto-backed / overcollateralized stablecoins to limit
// government / regulatory risk (e.g. USDC blacklisting until holders KYC)
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Reviewer(s) / Contributor(s)
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
// Dennis: github.com/denett
// Hameed
contract FraxPoolV3 is Owned {
using SafeMath for uint256;
// SafeMath automatically included in Solidity >= 8.0.0
/* ========== STATE VARIABLES ========== */
// Core
address public timelock_address;
address public custodian_address; // Custodian is an EOA (or msig) with pausing privileges only, in case of an emergency
IFrax private FRAX = IFrax(0x853d955aCEf822Db058eb8505911ED77F175b99e);
IFxs private FXS = IFxs(0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0);
mapping(address => bool) public amo_minter_addresses; // minter address -> is it enabled
AggregatorV3Interface public priceFeedFRAXUSD = AggregatorV3Interface(0xB9E1E3A9feFf48998E45Fa90847ed4D467E8BcfD);
AggregatorV3Interface public priceFeedFXSUSD = AggregatorV3Interface(0x6Ebc52C8C1089be9eB3945C4350B68B8E4C2233f);
uint256 private chainlink_frax_usd_decimals;
uint256 private chainlink_fxs_usd_decimals;
// Collateral
address[] public collateral_addresses;
string[] public collateral_symbols;
uint256[] public missing_decimals; // Number of decimals needed to get to E18. collateral index -> missing_decimals
uint256[] public pool_ceilings; // Total across all collaterals. Accounts for missing_decimals
uint256[] public collateral_prices; // Stores price of the collateral, if price is paused
mapping(address => uint256) public collateralAddrToIdx; // collateral addr -> collateral index
mapping(address => bool) public enabled_collaterals; // collateral address -> is it enabled
// Redeem related
mapping (address => uint256) public redeemFXSBalances;
mapping (address => mapping(uint256 => uint256)) public redeemCollateralBalances; // Address -> collateral index -> balance
uint256[] public unclaimedPoolCollateral; // collateral index -> balance
uint256 public unclaimedPoolFXS;
mapping (address => uint256) public lastRedeemed; // Collateral independent
uint256 public redemption_delay = 2; // Number of blocks to wait before being able to collectRedemption()
uint256 public redeem_price_threshold = 990000; // $0.99
uint256 public mint_price_threshold = 1010000; // $1.01
// Buyback related
mapping(uint256 => uint256) public bbkHourlyCum; // Epoch hour -> Collat out in that hour (E18)
uint256 public bbkMaxColE18OutPerHour = 1000e18;
// Recollat related
mapping(uint256 => uint256) public rctHourlyCum; // Epoch hour -> FXS out in that hour
uint256 public rctMaxFxsOutPerHour = 1000e18;
// Fees and rates
// getters are in collateral_information()
uint256[] private minting_fee;
uint256[] private redemption_fee;
uint256[] private buyback_fee;
uint256[] private recollat_fee;
uint256 public bonus_rate; // Bonus rate on FXS minted during recollateralize(); 6 decimals of precision, set to 0.75% on genesis
// Constants for various precisions
uint256 private constant PRICE_PRECISION = 1e6;
// Pause variables
// getters are in collateral_information()
bool[] private mintPaused; // Collateral-specific
bool[] private redeemPaused; // Collateral-specific
bool[] private recollateralizePaused; // Collateral-specific
bool[] private buyBackPaused; // Collateral-specific
/* ========== MODIFIERS ========== */
modifier onlyByOwnGov() {
require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock");
_;
}
modifier onlyByOwnGovCust() {
require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd");
_;
}
modifier onlyAMOMinters() {
require(amo_minter_addresses[msg.sender], "Not an AMO Minter");
_;
}
modifier collateralEnabled(uint256 col_idx) {
require(enabled_collaterals[collateral_addresses[col_idx]], "Collateral disabled");
_;
}
/* ========== CONSTRUCTOR ========== */
constructor (
address _pool_manager_address,
address _custodian_address,
address _timelock_address,
address[] memory _collateral_addresses,
uint256[] memory _pool_ceilings,
uint256[] memory _initial_fees
) Owned(_pool_manager_address){
// Core
timelock_address = _timelock_address;
custodian_address = _custodian_address;
// Fill collateral info
collateral_addresses = _collateral_addresses;
for (uint256 i = 0; i < _collateral_addresses.length; i++){
// For fast collateral address -> collateral idx lookups later
collateralAddrToIdx[_collateral_addresses[i]] = i;
// Set all of the collaterals initially to disabled
enabled_collaterals[_collateral_addresses[i]] = false;
// Add in the missing decimals
missing_decimals.push(uint256(18).sub(ERC20(_collateral_addresses[i]).decimals()));
// Add in the collateral symbols
collateral_symbols.push(ERC20(_collateral_addresses[i]).symbol());
// Initialize unclaimed pool collateral
unclaimedPoolCollateral.push(0);
// Initialize paused prices to $1 as a backup
collateral_prices.push(PRICE_PRECISION);
// Handle the fees
minting_fee.push(_initial_fees[0]);
redemption_fee.push(_initial_fees[1]);
buyback_fee.push(_initial_fees[2]);
recollat_fee.push(_initial_fees[3]);
// Handle the pauses
mintPaused.push(false);
redeemPaused.push(false);
recollateralizePaused.push(false);
buyBackPaused.push(false);
}
// Pool ceiling
pool_ceilings = _pool_ceilings;
// Set the decimals
chainlink_frax_usd_decimals = priceFeedFRAXUSD.decimals();
chainlink_fxs_usd_decimals = priceFeedFXSUSD.decimals();
}
/* ========== STRUCTS ========== */
struct CollateralInformation {
uint256 index;
string symbol;
address col_addr;
bool is_enabled;
uint256 missing_decs;
uint256 price;
uint256 pool_ceiling;
bool mint_paused;
bool redeem_paused;
bool recollat_paused;
bool buyback_paused;
uint256 minting_fee;
uint256 redemption_fee;
uint256 buyback_fee;
uint256 recollat_fee;
}
/* ========== VIEWS ========== */
// Helpful for UIs
function collateral_information(address collat_address) external view returns (CollateralInformation memory return_data){
require(enabled_collaterals[collat_address], "Invalid collateral");
// Get the index
uint256 idx = collateralAddrToIdx[collat_address];
return_data = CollateralInformation(
idx, // [0]
collateral_symbols[idx], // [1]
collat_address, // [2]
enabled_collaterals[collat_address], // [3]
missing_decimals[idx], // [4]
collateral_prices[idx], // [5]
pool_ceilings[idx], // [6]
mintPaused[idx], // [7]
redeemPaused[idx], // [8]
recollateralizePaused[idx], // [9]
buyBackPaused[idx], // [10]
minting_fee[idx], // [11]
redemption_fee[idx], // [12]
buyback_fee[idx], // [13]
recollat_fee[idx] // [14]
);
}
function allCollaterals() external view returns (address[] memory) {
return collateral_addresses;
}
function getFRAXPrice() public view returns (uint256) {
( , int price, , , ) = priceFeedFRAXUSD.latestRoundData();
return uint256(price).mul(PRICE_PRECISION).div(10 ** chainlink_frax_usd_decimals);
}
function getFXSPrice() public view returns (uint256) {
( , int price, , , ) = priceFeedFXSUSD.latestRoundData();
return uint256(price).mul(PRICE_PRECISION).div(10 ** chainlink_fxs_usd_decimals);
}
// Returns the FRAX value in collateral tokens
function getFRAXInCollateral(uint256 col_idx, uint256 frax_amount) public view returns (uint256) {
return frax_amount.mul(PRICE_PRECISION).div(10 ** missing_decimals[col_idx]).div(collateral_prices[col_idx]);
}
// Used by some functions.
function freeCollatBalance(uint256 col_idx) public view returns (uint256) {
return ERC20(collateral_addresses[col_idx]).balanceOf(address(this)).sub(unclaimedPoolCollateral[col_idx]);
}
// Returns dollar value of collateral held in this Frax pool, in E18
function collatDollarBalance() external view returns (uint256 balance_tally) {
balance_tally = 0;
// Test 1
for (uint256 i = 0; i < collateral_addresses.length; i++){
balance_tally += freeCollatBalance(i).mul(10 ** missing_decimals[i]).mul(collateral_prices[i]).div(PRICE_PRECISION);
}
}
function comboCalcBbkRct(uint256 cur, uint256 max, uint256 theo) internal pure returns (uint256) {
if (cur >= max) {
// If the hourly limit has already been reached, return 0;
return 0;
}
else {
// Get the available amount
uint256 available = max.sub(cur);
if (theo >= available) {
// If the the theoretical is more than the available, return the available
return available;
}
else {
// Otherwise, return the theoretical amount
return theo;
}
}
}
// Returns the value of excess collateral (in E18) held globally, compared to what is needed to maintain the global collateral ratio
// Also has throttling to avoid dumps during large price movements
function buybackAvailableCollat() public view returns (uint256) {
uint256 total_supply = FRAX.totalSupply();
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
uint256 global_collat_value = FRAX.globalCollateralValue();
if (global_collateral_ratio > PRICE_PRECISION) global_collateral_ratio = PRICE_PRECISION; // Handles an overcollateralized contract with CR > 1
uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(PRICE_PRECISION); // Calculates collateral needed to back each 1 FRAX with $1 of collateral at current collat ratio
if (global_collat_value > required_collat_dollar_value_d18) {
// Get the theoretical buyback amount
uint256 theoretical_bbk_amt = global_collat_value.sub(required_collat_dollar_value_d18);
// See how much has collateral has been issued this hour
uint256 current_hr_bbk = bbkHourlyCum[curEpochHr()];
// Account for the throttling
return comboCalcBbkRct(current_hr_bbk, bbkMaxColE18OutPerHour, theoretical_bbk_amt);
}
else return 0;
}
// Returns the missing amount of collateral (in E18) needed to maintain the collateral ratio
function recollatTheoColAvailableE18() public view returns (uint256) {
uint256 frax_total_supply = FRAX.totalSupply();
uint256 effective_collateral_ratio = FRAX.globalCollateralValue().mul(PRICE_PRECISION).div(frax_total_supply); // Returns it in 1e6
uint256 desired_collat_e24 = (FRAX.global_collateral_ratio()).mul(frax_total_supply);
uint256 effective_collat_e24 = effective_collateral_ratio.mul(frax_total_supply);
// Return 0 if already overcollateralized
// Otherwise, return the deficiency
if (effective_collat_e24 >= desired_collat_e24) return 0;
else {
return (desired_collat_e24.sub(effective_collat_e24)).div(PRICE_PRECISION);
}
}
// Returns the value of FXS available to be used for recollats
// Also has throttling to avoid dumps during large price movements
function recollatAvailableFxs() public view returns (uint256) {
uint256 fxs_price = getFXSPrice();
// Get the amount of collateral theoretically available
uint256 recollat_theo_available_e18 = recollatTheoColAvailableE18();
// Get the amount of FXS theoretically outputtable
uint256 fxs_theo_out = recollat_theo_available_e18.mul(PRICE_PRECISION).div(fxs_price);
// See how much FXS has been issued this hour
uint256 current_hr_rct = rctHourlyCum[curEpochHr()];
// Account for the throttling
return comboCalcBbkRct(current_hr_rct, rctMaxFxsOutPerHour, fxs_theo_out);
}
// Returns the current epoch hour
function curEpochHr() public view returns (uint256) {
return (block.timestamp / 3600); // Truncation desired
}
/* ========== PUBLIC FUNCTIONS ========== */
function mintFrax(
uint256 col_idx,
uint256 frax_amt,
uint256 frax_out_min,
bool one_to_one_override
) external collateralEnabled(col_idx) returns (
uint256 total_frax_mint,
uint256 collat_needed,
uint256 fxs_needed
) {
require(mintPaused[col_idx] == false, "Minting is paused");
// Prevent unneccessary mints
require(getFRAXPrice() >= mint_price_threshold, "Frax price too low");
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
if (one_to_one_override || global_collateral_ratio >= PRICE_PRECISION) {
// 1-to-1, overcollateralized, or user selects override
collat_needed = getFRAXInCollateral(col_idx, frax_amt);
fxs_needed = 0;
} else if (global_collateral_ratio == 0) {
// Algorithmic
collat_needed = 0;
fxs_needed = frax_amt.mul(PRICE_PRECISION).div(getFXSPrice());
} else {
// Fractional
uint256 frax_for_collat = frax_amt.mul(global_collateral_ratio).div(PRICE_PRECISION);
uint256 frax_for_fxs = frax_amt.sub(frax_for_collat);
collat_needed = getFRAXInCollateral(col_idx, frax_for_collat);
fxs_needed = frax_for_fxs.mul(PRICE_PRECISION).div(getFXSPrice());
}
// Subtract the minting fee
total_frax_mint = (frax_amt.mul(PRICE_PRECISION.sub(minting_fee[col_idx]))).div(PRICE_PRECISION);
// Checks
require((frax_out_min <= total_frax_mint), "FRAX slippage");
require(freeCollatBalance(col_idx).add(collat_needed) <= pool_ceilings[col_idx], "Pool ceiling");
// Take the FXS and collateral first
FXS.pool_burn_from(msg.sender, fxs_needed);
TransferHelper.safeTransferFrom(collateral_addresses[col_idx], msg.sender, address(this), collat_needed);
// Mint the FRAX
FRAX.pool_mint(msg.sender, total_frax_mint);
}
function redeemFrax(
uint256 col_idx,
uint256 frax_amount,
uint256 fxs_out_min,
uint256 col_out_min
) external collateralEnabled(col_idx) returns (
uint256 collat_out,
uint256 fxs_out
) {
require(redeemPaused[col_idx] == false, "Redeeming is paused");
// Prevent unneccessary redemptions that could adversely affect the FXS price
require(getFRAXPrice() <= redeem_price_threshold, "Frax price too high");
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
uint256 frax_after_fee = (frax_amount.mul(PRICE_PRECISION.sub(redemption_fee[col_idx]))).div(PRICE_PRECISION);
// Assumes $1 FRAX in all cases
if(global_collateral_ratio >= PRICE_PRECISION) {
// 1-to-1 or overcollateralized
collat_out = frax_after_fee
.mul(collateral_prices[col_idx])
.div(10 ** (6 + missing_decimals[col_idx])); // PRICE_PRECISION + missing decimals
fxs_out = 0;
} else if (global_collateral_ratio == 0) {
// Algorithmic
fxs_out = frax_after_fee
.mul(PRICE_PRECISION)
.div(getFXSPrice());
collat_out = 0;
} else {
// Fractional
collat_out = frax_after_fee
.mul(global_collateral_ratio)
.mul(collateral_prices[col_idx])
.div(10 ** (12 + missing_decimals[col_idx])); // PRICE_PRECISION ^2 + missing decimals
fxs_out = frax_after_fee
.mul(PRICE_PRECISION.sub(global_collateral_ratio))
.div(getFXSPrice()); // PRICE_PRECISIONS CANCEL OUT
}
// Checks
require(collat_out <= (ERC20(collateral_addresses[col_idx])).balanceOf(address(this)).sub(unclaimedPoolCollateral[col_idx]), "Insufficient pool collateral");
require(collat_out >= col_out_min, "Collateral slippage");
require(fxs_out >= fxs_out_min, "FXS slippage");
// Account for the redeem delay
redeemCollateralBalances[msg.sender][col_idx] = redeemCollateralBalances[msg.sender][col_idx].add(collat_out);
unclaimedPoolCollateral[col_idx] = unclaimedPoolCollateral[col_idx].add(collat_out);
redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_out);
unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_out);
lastRedeemed[msg.sender] = block.number;
FRAX.pool_burn_from(msg.sender, frax_amount);
FXS.pool_mint(address(this), fxs_out);
}
// After a redemption happens, transfer the newly minted FXS and owed collateral from this pool
// contract to the user. Redemption is split into two functions to prevent flash loans from being able
// to take out FRAX/collateral from the system, use an AMM to trade the new price, and then mint back into the system.
function collectRedemption(uint256 col_idx) external returns (uint256 fxs_amount, uint256 collateral_amount) {
require(redeemPaused[col_idx] == false, "Redeeming is paused");
require((lastRedeemed[msg.sender].add(redemption_delay)) <= block.number, "Too soon");
bool sendFXS = false;
bool sendCollateral = false;
// Use Checks-Effects-Interactions pattern
if(redeemFXSBalances[msg.sender] > 0){
fxs_amount = redeemFXSBalances[msg.sender];
redeemFXSBalances[msg.sender] = 0;
unclaimedPoolFXS = unclaimedPoolFXS.sub(fxs_amount);
sendFXS = true;
}
if(redeemCollateralBalances[msg.sender][col_idx] > 0){
collateral_amount = redeemCollateralBalances[msg.sender][col_idx];
redeemCollateralBalances[msg.sender][col_idx] = 0;
unclaimedPoolCollateral[col_idx] = unclaimedPoolCollateral[col_idx].sub(collateral_amount);
sendCollateral = true;
}
// Send out the tokens
if(sendFXS){
TransferHelper.safeTransfer(address(FXS), msg.sender, fxs_amount);
}
if(sendCollateral){
TransferHelper.safeTransfer(collateral_addresses[col_idx], msg.sender, collateral_amount);
}
}
// Function can be called by an FXS holder to have the protocol buy back FXS with excess collateral value from a desired collateral pool
// This can also happen if the collateral ratio > 1
function buyBackFxs(uint256 col_idx, uint256 fxs_amount, uint256 col_out_min) external collateralEnabled(col_idx) returns (uint256 col_out) {
require(buyBackPaused[col_idx] == false, "Buyback is paused");
uint256 fxs_price = getFXSPrice();
uint256 available_excess_collat_dv = buybackAvailableCollat();
// If the total collateral value is higher than the amount required at the current collateral ratio then buy back up to the possible FXS with the desired collateral
require(available_excess_collat_dv > 0, "Insuf Collat Avail For BBK");
// Make sure not to take more than is available
uint256 fxs_dollar_value_d18 = fxs_amount.mul(fxs_price).div(PRICE_PRECISION);
require(fxs_dollar_value_d18 <= available_excess_collat_dv, "Insuf Collat Avail For BBK");
// Get the equivalent amount of collateral based on the market value of FXS provided
uint256 collateral_equivalent_d18 = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(collateral_prices[col_idx]);
col_out = collateral_equivalent_d18.div(10 ** missing_decimals[col_idx]); // In its natural decimals()
// Subtract the buyback fee
col_out = (col_out.mul(PRICE_PRECISION.sub(buyback_fee[col_idx]))).div(PRICE_PRECISION);
// Check for slippage
require(col_out >= col_out_min, "Collateral slippage");
// Take in and burn the FXS, then send out the collateral
FXS.pool_burn_from(msg.sender, fxs_amount);
TransferHelper.safeTransfer(collateral_addresses[col_idx], msg.sender, col_out);
// Increment the outbound collateral, in E18, for that hour
// Used for buyback throttling
bbkHourlyCum[curEpochHr()] += collateral_equivalent_d18;
}
// When the protocol is recollateralizing, we need to give a discount of FXS to hit the new CR target
// Thus, if the target collateral ratio is higher than the actual value of collateral, minters get FXS for adding collateral
// This function simply rewards anyone that sends collateral to a pool with the same amount of FXS + the bonus rate
// Anyone can call this function to recollateralize the protocol and take the extra FXS value from the bonus rate as an arb opportunity
function recollateralize(uint256 col_idx, uint256 collateral_amount, uint256 fxs_out_min) external collateralEnabled(col_idx) returns (uint256 fxs_out) {
require(recollateralizePaused[col_idx] == false, "Recollat is paused");
uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals[col_idx]);
uint256 fxs_price = getFXSPrice();
// Get the amount of FXS actually available (accounts for throttling)
uint256 fxs_actually_available = recollatAvailableFxs();
// Calculated the attempted amount of FXS
fxs_out = collateral_amount_d18.mul(PRICE_PRECISION.add(bonus_rate).sub(recollat_fee[col_idx])).div(fxs_price);
// Make sure there is FXS available
require(fxs_out <= fxs_actually_available, "Insuf FXS Avail For RCT");
// Check slippage
require(fxs_out >= fxs_out_min, "FXS slippage");
// Don't take in more collateral than the pool ceiling for this token allows
require(freeCollatBalance(col_idx).add(collateral_amount) <= pool_ceilings[col_idx], "Pool ceiling");
// Take in the collateral and pay out the FXS
TransferHelper.safeTransferFrom(collateral_addresses[col_idx], msg.sender, address(this), collateral_amount);
FXS.pool_mint(msg.sender, fxs_out);
// Increment the outbound FXS, in E18
// Used for recollat throttling
rctHourlyCum[curEpochHr()] += fxs_out;
}
// Bypasses the gassy mint->redeem cycle for AMOs to borrow collateral
function amoMinterBorrow(uint256 collateral_amount) external onlyAMOMinters {
// Checks the col_idx of the minter as an additional safety check
uint256 minter_col_idx = IFraxAMOMinter(msg.sender).col_idx();
// Transfer
TransferHelper.safeTransfer(collateral_addresses[minter_col_idx], msg.sender, collateral_amount);
}
/* ========== RESTRICTED FUNCTIONS, CUSTODIAN CAN CALL TOO ========== */
function toggleMRBR(uint256 col_idx, uint8 tog_idx) external onlyByOwnGovCust {
if (tog_idx == 0) mintPaused[col_idx] = !mintPaused[col_idx];
else if (tog_idx == 1) redeemPaused[col_idx] = !redeemPaused[col_idx];
else if (tog_idx == 2) buyBackPaused[col_idx] = !buyBackPaused[col_idx];
else if (tog_idx == 3) recollateralizePaused[col_idx] = !recollateralizePaused[col_idx];
emit MRBRToggled(col_idx, tog_idx);
}
/* ========== RESTRICTED FUNCTIONS, GOVERNANCE ONLY ========== */
// Add an AMO Minter
function addAMOMinter(address amo_minter_addr) external onlyByOwnGov {
require(amo_minter_addr != address(0), "Zero address detected");
// Make sure the AMO Minter has collatDollarBalance()
uint256 collat_val_e18 = IFraxAMOMinter(amo_minter_addr).collatDollarBalance();
require(collat_val_e18 >= 0, "Invalid AMO");
amo_minter_addresses[amo_minter_addr] = true;
emit AMOMinterAdded(amo_minter_addr);
}
// Remove an AMO Minter
function removeAMOMinter(address amo_minter_addr) external onlyByOwnGov {
amo_minter_addresses[amo_minter_addr] = false;
emit AMOMinterRemoved(amo_minter_addr);
}
function setCollateralPrice(uint256 col_idx, uint256 _new_price) external onlyByOwnGov {
collateral_prices[col_idx] = _new_price;
emit CollateralPriceSet(col_idx, _new_price);
}
// Could also be called toggleCollateral
function toggleCollateral(uint256 col_idx) external onlyByOwnGov {
address col_address = collateral_addresses[col_idx];
enabled_collaterals[col_address] = !enabled_collaterals[col_address];
emit CollateralToggled(col_idx, enabled_collaterals[col_address]);
}
function setPoolCeiling(uint256 col_idx, uint256 new_ceiling) external onlyByOwnGov {
pool_ceilings[col_idx] = new_ceiling;
emit PoolCeilingSet(col_idx, new_ceiling);
}
function setFees(uint256 col_idx, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee) external onlyByOwnGov {
minting_fee[col_idx] = new_mint_fee;
redemption_fee[col_idx] = new_redeem_fee;
buyback_fee[col_idx] = new_buyback_fee;
recollat_fee[col_idx] = new_recollat_fee;
emit FeesSet(col_idx, new_mint_fee, new_redeem_fee, new_buyback_fee, new_recollat_fee);
}
function setPoolParameters(uint256 new_bonus_rate, uint256 new_redemption_delay) external onlyByOwnGov {
bonus_rate = new_bonus_rate;
redemption_delay = new_redemption_delay;
emit PoolParametersSet(new_bonus_rate, new_redemption_delay);
}
function setPriceThresholds(uint256 new_mint_price_threshold, uint256 new_redeem_price_threshold) external onlyByOwnGov {
mint_price_threshold = new_mint_price_threshold;
redeem_price_threshold = new_redeem_price_threshold;
emit PriceThresholdsSet(new_mint_price_threshold, new_redeem_price_threshold);
}
function setBbkRctPerHour(uint256 _bbkMaxColE18OutPerHour, uint256 _rctMaxFxsOutPerHour) external onlyByOwnGov {
bbkMaxColE18OutPerHour = _bbkMaxColE18OutPerHour;
rctMaxFxsOutPerHour = _rctMaxFxsOutPerHour;
emit BbkRctPerHourSet(_bbkMaxColE18OutPerHour, _rctMaxFxsOutPerHour);
}
// Set the Chainlink oracles
function setOracles(address _frax_usd_chainlink_addr, address _fxs_usd_chainlink_addr) external onlyByOwnGov {
// Set the instances
priceFeedFRAXUSD = AggregatorV3Interface(_frax_usd_chainlink_addr);
priceFeedFXSUSD = AggregatorV3Interface(_fxs_usd_chainlink_addr);
// Set the decimals
chainlink_frax_usd_decimals = priceFeedFRAXUSD.decimals();
chainlink_fxs_usd_decimals = priceFeedFXSUSD.decimals();
emit OraclesSet(_frax_usd_chainlink_addr, _fxs_usd_chainlink_addr);
}
function setCustodian(address new_custodian) external onlyByOwnGov {
custodian_address = new_custodian;
emit CustodianSet(new_custodian);
}
function setTimelock(address new_timelock) external onlyByOwnGov {
timelock_address = new_timelock;
emit TimelockSet(new_timelock);
}
/* ========== EVENTS ========== */
event CollateralToggled(uint256 col_idx, bool new_state);
event PoolCeilingSet(uint256 col_idx, uint256 new_ceiling);
event FeesSet(uint256 col_idx, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee);
event PoolParametersSet(uint256 new_bonus_rate, uint256 new_redemption_delay);
event PriceThresholdsSet(uint256 new_bonus_rate, uint256 new_redemption_delay);
event BbkRctPerHourSet(uint256 bbkMaxColE18OutPerHour, uint256 rctMaxFxsOutPerHour);
event AMOMinterAdded(address amo_minter_addr);
event AMOMinterRemoved(address amo_minter_addr);
event OraclesSet(address frax_usd_chainlink_addr, address fxs_usd_chainlink_addr);
event CustodianSet(address new_custodian);
event TimelockSet(address new_timelock);
event MRBRToggled(uint256 col_idx, uint8 tog_idx);
event CollateralPriceSet(uint256 col_idx, uint256 new_price);
}
// File contracts/Uniswap/Interfaces/IUniswapV2Factory.sol
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// File contracts/Uniswap/Interfaces/IUniswapV2Pair.sol
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/Math/Babylonian.sol
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
// else z = 0
}
}
// File contracts/Math/FixedPoint.sol
// 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;
uint private constant Q112 = uint(1) << RESOLUTION;
uint private constant Q224 = Q112 << RESOLUTION;
// 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);
}
// take the reciprocal of a UQ112x112
function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) {
require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL');
return uq112x112(uint224(Q224 / self._x));
}
// square root of a UQ112x112
function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56));
}
}
// File contracts/Uniswap/UniswapV2OracleLibrary.sol
// 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;
}
}
}
// File contracts/Uniswap/UniswapV2Library.sol
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');
}
// Less efficient than the CREATE2 method below
function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = IUniswapV2Factory(factory).getPair(token0, token1);
}
// calculates the CREATE2 address for a pair without making any external calls
function pairForCreate2(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint160(bytes20(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))))); // this matches the CREATE2 in UniswapV2Factory.createPair
}
// 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 = 0; 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/Oracle/UniswapPairOracle.sol
// 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 UniswapPairOracle is Owned {
using FixedPoint for *;
address timelock_address;
uint public PERIOD = 3600; // 1 hour TWAP (time-weighted average price)
uint public CONSULT_LENIENCY = 120; // Used for being able to consult past the period end
bool public ALLOW_STALE_CONSULTS = false; // If false, consult() will fail if the TWAP is stale
IUniswapV2Pair public 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;
modifier onlyByOwnGov() {
require(msg.sender == owner || msg.sender == timelock_address, "You are not an owner or the governance timelock");
_;
}
constructor (
address factory,
address tokenA,
address tokenB,
address _owner_address,
address _timelock_address
) public Owned(_owner_address) {
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();
require(reserve0 != 0 && reserve1 != 0, 'UniswapPairOracle: NO_RESERVES'); // Ensure that there's liquidity in the pair
timelock_address = _timelock_address;
}
function setTimelock(address _timelock_address) external onlyByOwnGov {
timelock_address = _timelock_address;
}
function setPeriod(uint _period) external onlyByOwnGov {
PERIOD = _period;
}
function setConsultLeniency(uint _consult_leniency) external onlyByOwnGov {
CONSULT_LENIENCY = _consult_leniency;
}
function setAllowStaleConsults(bool _allow_stale_consults) external onlyByOwnGov {
ALLOW_STALE_CONSULTS = _allow_stale_consults;
}
// Check if update() can be called instead of wasting gas calling it
function canUpdate() public view returns (bool) {
uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp();
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired
return (timeElapsed >= PERIOD);
}
function update() external {
(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, 'UniswapPairOracle: 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) public view returns (uint amountOut) {
uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp();
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired
// Ensure that the price is not stale
require((timeElapsed < (PERIOD + CONSULT_LENIENCY)) || ALLOW_STALE_CONSULTS, 'UniswapPairOracle: PRICE_IS_STALE_NEED_TO_CALL_UPDATE');
if (token == token0) {
amountOut = price0Average.mul(amountIn).decode144();
} else {
require(token == token1, 'UniswapPairOracle: INVALID_TOKEN');
amountOut = price1Average.mul(amountIn).decode144();
}
}
}
// File contracts/Uniswap/Interfaces/IUniswapV2Router01.sol
interface IUniswapV2Router01 {
function factory() external returns (address);
function WETH() external 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);
}
// File contracts/Uniswap/Interfaces/IUniswapV2Router02.sol
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// File contracts/Proxy/Initializable.sol
// solhint-disable-next-line compiler-version
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// File contracts/Math/Math.sol
/**
* @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);
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// File contracts/Curve/IveFXS.sol
pragma abicoder v2;
interface IveFXS {
struct LockedBalance {
int128 amount;
uint256 end;
}
function commit_transfer_ownership(address addr) external;
function apply_transfer_ownership() external;
function commit_smart_wallet_checker(address addr) external;
function apply_smart_wallet_checker() external;
function toggleEmergencyUnlock() external;
function recoverERC20(address token_addr, uint256 amount) external;
function get_last_user_slope(address addr) external view returns (int128);
function user_point_history__ts(address _addr, uint256 _idx) external view returns (uint256);
function locked__end(address _addr) external view returns (uint256);
function checkpoint() external;
function deposit_for(address _addr, uint256 _value) external;
function create_lock(uint256 _value, uint256 _unlock_time) external;
function increase_amount(uint256 _value) external;
function increase_unlock_time(uint256 _unlock_time) external;
function withdraw() external;
function balanceOf(address addr) external view returns (uint256);
function balanceOf(address addr, uint256 _t) external view returns (uint256);
function balanceOfAt(address addr, uint256 _block) external view returns (uint256);
function totalSupply() external view returns (uint256);
function totalSupply(uint256 t) external view returns (uint256);
function totalSupplyAt(uint256 _block) external view returns (uint256);
function totalFXSSupply() external view returns (uint256);
function totalFXSSupplyAt(uint256 _block) external view returns (uint256);
function changeController(address _newController) external;
function token() external view returns (address);
function supply() external view returns (uint256);
function locked(address addr) external view returns (LockedBalance memory);
function epoch() external view returns (uint256);
function point_history(uint256 arg0) external view returns (int128 bias, int128 slope, uint256 ts, uint256 blk, uint256 fxs_amt);
function user_point_history(address arg0, uint256 arg1) external view returns (int128 bias, int128 slope, uint256 ts, uint256 blk, uint256 fxs_amt);
function user_point_epoch(address arg0) external view returns (uint256);
function slope_changes(uint256 arg0) external view returns (int128);
function controller() external view returns (address);
function transfersEnabled() external view returns (bool);
function emergencyUnlockActive() external view returns (bool);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function version() external view returns (string memory);
function decimals() external view returns (uint256);
function future_smart_wallet_checker() external view returns (address);
function smart_wallet_checker() external view returns (address);
function admin() external view returns (address);
function future_admin() external view returns (address);
}
// File contracts/ERC20/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for 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/Utils/ReentrancyGuard.sol
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File contracts/Staking/veFXSYieldDistributorV4.sol
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ======================veFXSYieldDistributorV4=======================
// ====================================================================
// Distributes Frax protocol yield based on the claimer's veFXS balance
// V3: Yield will now not accrue for unlocked veFXS
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Reviewer(s) / Contributor(s)
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
// Originally inspired by Synthetix.io, but heavily modified by the Frax team (veFXS portion)
// https://github.com/Synthetixio/synthetix/blob/develop/contracts/StakingRewards.sol
contract veFXSYieldDistributorV4 is Owned, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for ERC20;
/* ========== STATE VARIABLES ========== */
// Instances
IveFXS private veFXS;
ERC20 public emittedToken;
// Addresses
address public emitted_token_address;
// Admin addresses
address public timelock_address;
// Constant for price precision
uint256 private constant PRICE_PRECISION = 1e6;
// Yield and period related
uint256 public periodFinish;
uint256 public lastUpdateTime;
uint256 public yieldRate;
uint256 public yieldDuration = 604800; // 7 * 86400 (7 days)
mapping(address => bool) public reward_notifiers;
// Yield tracking
uint256 public yieldPerVeFXSStored = 0;
mapping(address => uint256) public userYieldPerTokenPaid;
mapping(address => uint256) public yields;
// veFXS tracking
uint256 public totalVeFXSParticipating = 0;
uint256 public totalVeFXSSupplyStored = 0;
mapping(address => bool) public userIsInitialized;
mapping(address => uint256) public userVeFXSCheckpointed;
mapping(address => uint256) public userVeFXSEndpointCheckpointed;
mapping(address => uint256) private lastRewardClaimTime; // staker addr -> timestamp
// Greylists
mapping(address => bool) public greylist;
// Admin booleans for emergencies
bool public yieldCollectionPaused = false; // For emergencies
struct LockedBalance {
int128 amount;
uint256 end;
}
/* ========== MODIFIERS ========== */
modifier onlyByOwnGov() {
require( msg.sender == owner || msg.sender == timelock_address, "Not owner or timelock");
_;
}
modifier notYieldCollectionPaused() {
require(yieldCollectionPaused == false, "Yield collection is paused");
_;
}
modifier checkpointUser(address account) {
_checkpointUser(account);
_;
}
/* ========== CONSTRUCTOR ========== */
constructor (
address _owner,
address _emittedToken,
address _timelock_address,
address _veFXS_address
) Owned(_owner) {
emitted_token_address = _emittedToken;
emittedToken = ERC20(_emittedToken);
veFXS = IveFXS(_veFXS_address);
lastUpdateTime = block.timestamp;
timelock_address = _timelock_address;
reward_notifiers[_owner] = true;
}
/* ========== VIEWS ========== */
function fractionParticipating() external view returns (uint256) {
return totalVeFXSParticipating.mul(PRICE_PRECISION).div(totalVeFXSSupplyStored);
}
// Only positions with locked veFXS can accrue yield. Otherwise, expired-locked veFXS
// is de-facto rewards for FXS.
function eligibleCurrentVeFXS(address account) public view returns (uint256 eligible_vefxs_bal, uint256 stored_ending_timestamp) {
uint256 curr_vefxs_bal = veFXS.balanceOf(account);
// Stored is used to prevent abuse
stored_ending_timestamp = userVeFXSEndpointCheckpointed[account];
// Only unexpired veFXS should be eligible
if (stored_ending_timestamp != 0 && (block.timestamp >= stored_ending_timestamp)){
eligible_vefxs_bal = 0;
}
else if (block.timestamp >= stored_ending_timestamp){
eligible_vefxs_bal = 0;
}
else {
eligible_vefxs_bal = curr_vefxs_bal;
}
}
function lastTimeYieldApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function yieldPerVeFXS() public view returns (uint256) {
if (totalVeFXSSupplyStored == 0) {
return yieldPerVeFXSStored;
} else {
return (
yieldPerVeFXSStored.add(
lastTimeYieldApplicable()
.sub(lastUpdateTime)
.mul(yieldRate)
.mul(1e18)
.div(totalVeFXSSupplyStored)
)
);
}
}
function earned(address account) public view returns (uint256) {
// Uninitialized users should not earn anything yet
if (!userIsInitialized[account]) return 0;
// Get eligible veFXS balances
(uint256 eligible_current_vefxs, uint256 ending_timestamp) = eligibleCurrentVeFXS(account);
// If your veFXS is unlocked
uint256 eligible_time_fraction = PRICE_PRECISION;
if (eligible_current_vefxs == 0){
// And you already claimed after expiration
if (lastRewardClaimTime[account] >= ending_timestamp) {
// You get NOTHING. You LOSE. Good DAY ser!
return 0;
}
// You haven't claimed yet
else {
uint256 eligible_time = (ending_timestamp).sub(lastRewardClaimTime[account]);
uint256 total_time = (block.timestamp).sub(lastRewardClaimTime[account]);
eligible_time_fraction = PRICE_PRECISION.mul(eligible_time).div(total_time);
}
}
// If the amount of veFXS increased, only pay off based on the old balance
// Otherwise, take the midpoint
uint256 vefxs_balance_to_use;
{
uint256 old_vefxs_balance = userVeFXSCheckpointed[account];
if (eligible_current_vefxs > old_vefxs_balance){
vefxs_balance_to_use = old_vefxs_balance;
}
else {
vefxs_balance_to_use = ((eligible_current_vefxs).add(old_vefxs_balance)).div(2);
}
}
return (
vefxs_balance_to_use
.mul(yieldPerVeFXS().sub(userYieldPerTokenPaid[account]))
.mul(eligible_time_fraction)
.div(1e18 * PRICE_PRECISION)
.add(yields[account])
);
}
function getYieldForDuration() external view returns (uint256) {
return (yieldRate.mul(yieldDuration));
}
/* ========== MUTATIVE FUNCTIONS ========== */
function _checkpointUser(address account) internal {
// Need to retro-adjust some things if the period hasn't been renewed, then start a new one
sync();
// Calculate the earnings first
_syncEarned(account);
// Get the old and the new veFXS balances
uint256 old_vefxs_balance = userVeFXSCheckpointed[account];
uint256 new_vefxs_balance = veFXS.balanceOf(account);
// Update the user's stored veFXS balance
userVeFXSCheckpointed[account] = new_vefxs_balance;
// Update the user's stored ending timestamp
IveFXS.LockedBalance memory curr_locked_bal_pack = veFXS.locked(account);
userVeFXSEndpointCheckpointed[account] = curr_locked_bal_pack.end;
// Update the total amount participating
if (new_vefxs_balance >= old_vefxs_balance) {
uint256 weight_diff = new_vefxs_balance.sub(old_vefxs_balance);
totalVeFXSParticipating = totalVeFXSParticipating.add(weight_diff);
} else {
uint256 weight_diff = old_vefxs_balance.sub(new_vefxs_balance);
totalVeFXSParticipating = totalVeFXSParticipating.sub(weight_diff);
}
// Mark the user as initialized
if (!userIsInitialized[account]) {
userIsInitialized[account] = true;
lastRewardClaimTime[account] = block.timestamp;
}
}
function _syncEarned(address account) internal {
if (account != address(0)) {
uint256 earned0 = earned(account);
yields[account] = earned0;
userYieldPerTokenPaid[account] = yieldPerVeFXSStored;
}
}
// Anyone can checkpoint another user
function checkpointOtherUser(address user_addr) external {
_checkpointUser(user_addr);
}
// Checkpoints the user
function checkpoint() external {
_checkpointUser(msg.sender);
}
function getYield() external nonReentrant notYieldCollectionPaused checkpointUser(msg.sender) returns (uint256 yield0) {
require(greylist[msg.sender] == false, "Address has been greylisted");
yield0 = yields[msg.sender];
if (yield0 > 0) {
yields[msg.sender] = 0;
TransferHelper.safeTransfer(
emitted_token_address,
msg.sender,
yield0
);
emit YieldCollected(msg.sender, yield0, emitted_token_address);
}
lastRewardClaimTime[msg.sender] = block.timestamp;
}
function sync() public {
// Update the total veFXS supply
yieldPerVeFXSStored = yieldPerVeFXS();
totalVeFXSSupplyStored = veFXS.totalSupply();
lastUpdateTime = lastTimeYieldApplicable();
}
function notifyRewardAmount(uint256 amount) external {
// Only whitelisted addresses can notify rewards
require(reward_notifiers[msg.sender], "Sender not whitelisted");
// Handle the transfer of emission tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the smission amount
emittedToken.safeTransferFrom(msg.sender, address(this), amount);
// Update some values beforehand
sync();
// Update the new yieldRate
if (block.timestamp >= periodFinish) {
yieldRate = amount.div(yieldDuration);
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(yieldRate);
yieldRate = amount.add(leftover).div(yieldDuration);
}
// Update duration-related info
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(yieldDuration);
emit RewardAdded(amount, yieldRate);
}
/* ========== RESTRICTED FUNCTIONS ========== */
// Added to support recovering LP Yield and other mistaken tokens from other systems to be distributed to holders
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov {
// Only the owner address can ever receive the recovery withdrawal
TransferHelper.safeTransfer(tokenAddress, owner, tokenAmount);
emit RecoveredERC20(tokenAddress, tokenAmount);
}
function setYieldDuration(uint256 _yieldDuration) external onlyByOwnGov {
require( periodFinish == 0 || block.timestamp > periodFinish, "Previous yield period must be complete before changing the duration for the new period");
yieldDuration = _yieldDuration;
emit YieldDurationUpdated(yieldDuration);
}
function greylistAddress(address _address) external onlyByOwnGov {
greylist[_address] = !(greylist[_address]);
}
function toggleRewardNotifier(address notifier_addr) external onlyByOwnGov {
reward_notifiers[notifier_addr] = !reward_notifiers[notifier_addr];
}
function setPauses(bool _yieldCollectionPaused) external onlyByOwnGov {
yieldCollectionPaused = _yieldCollectionPaused;
}
function setYieldRate(uint256 _new_rate0, bool sync_too) external onlyByOwnGov {
yieldRate = _new_rate0;
if (sync_too) {
sync();
}
}
function setTimelock(address _new_timelock) external onlyByOwnGov {
timelock_address = _new_timelock;
}
/* ========== EVENTS ========== */
event RewardAdded(uint256 reward, uint256 yieldRate);
event OldYieldCollected(address indexed user, uint256 yield, address token_address);
event YieldCollected(address indexed user, uint256 yield, address token_address);
event YieldDurationUpdated(uint256 newDuration);
event RecoveredERC20(address token, uint256 amount);
event YieldPeriodRenewed(address token, uint256 yieldRate);
event DefaultInitialization();
/* ========== A CHICKEN ========== */
//
// ,~.
// ,-'__ `-,
// {,-' `. } ,')
// ,( a ) `-.__ ,',')~,
// <=.) ( `-.__,==' ' ' '}
// ( ) /)
// `-'\ , )
// | \ `~. /
// \ `._ \ /
// \ `._____,' ,'
// `-. ,'
// `-._ _,-'
// 77jj'
// //_||
// __//--'/`
// ,--'/` '
//
// [hjw] https://textart.io/art/vw6Sa3iwqIRGkZsN1BC2vweF/chicken
}
// File contracts/Misc_AMOs/FXS1559_AMO_V3.sol
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ========================== FXS1559_AMO_V3 ==========================
// ====================================================================
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Reviewer(s) / Contributor(s)
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
contract FXS1559_AMO_V3 is Owned {
using SafeMath for uint256;
// SafeMath automatically included in Solidity >= 8.0.0
/* ========== STATE VARIABLES ========== */
ERC20 private collateral_token;
IFrax private FRAX;
IFxs private FXS;
IUniswapV2Router02 private UniRouterV2;
IFraxAMOMinter public amo_minter;
FraxPoolV3 public pool = FraxPoolV3(0x2fE065e6FFEf9ac95ab39E5042744d695F560729);
veFXSYieldDistributorV4 public yieldDistributor;
address private constant collateral_address = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address public timelock_address;
address public custodian_address;
address private constant frax_address = 0x853d955aCEf822Db058eb8505911ED77F175b99e;
address private constant fxs_address = 0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0;
address payable public constant UNISWAP_ROUTER_ADDRESS = payable(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public amo_minter_address;
uint256 private missing_decimals;
uint256 private constant PRICE_PRECISION = 1e6;
uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6;
// FRAX -> FXS max slippage
uint256 public max_slippage;
// Burned vs given to yield distributor
uint256 public burn_fraction; // E6. Fraction of FXS burned vs transferred to the yield distributor
/* ========== CONSTRUCTOR ========== */
constructor (
address _owner_address,
address _yield_distributor_address,
address _amo_minter_address
) Owned(_owner_address) {
owner = _owner_address;
FRAX = IFrax(frax_address);
FXS = IFxs(fxs_address);
collateral_token = ERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
missing_decimals = uint(18).sub(collateral_token.decimals());
yieldDistributor = veFXSYieldDistributorV4(_yield_distributor_address);
// Initializations
UniRouterV2 = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
amo_minter = IFraxAMOMinter(_amo_minter_address);
max_slippage = 50000; // 5%
burn_fraction = 0; // Give all to veFXS initially
// Get the custodian and timelock addresses from the minter
custodian_address = amo_minter.custodian_address();
timelock_address = amo_minter.timelock_address();
}
/* ========== MODIFIERS ========== */
modifier onlyByOwnGov() {
require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock");
_;
}
modifier onlyByOwnGovCust() {
require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd");
_;
}
modifier onlyByMinter() {
require(msg.sender == address(amo_minter), "Not minter");
_;
}
/* ========== VIEWS ========== */
function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) {
frax_val_e18 = 1e18;
collat_val_e18 = 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _swapFRAXforFXS(uint256 frax_amount) internal returns (uint256 frax_spent, uint256 fxs_received) {
// Get the FXS price
uint256 fxs_price = pool.getFXSPrice();
// Approve the FRAX for the router
FRAX.approve(UNISWAP_ROUTER_ADDRESS, frax_amount);
address[] memory FRAX_FXS_PATH = new address[](2);
FRAX_FXS_PATH[0] = frax_address;
FRAX_FXS_PATH[1] = fxs_address;
uint256 min_fxs_out = frax_amount.mul(PRICE_PRECISION).div(fxs_price);
min_fxs_out = min_fxs_out.sub(min_fxs_out.mul(max_slippage).div(PRICE_PRECISION));
// Buy some FXS with FRAX
(uint[] memory amounts) = UniRouterV2.swapExactTokensForTokens(
frax_amount,
min_fxs_out,
FRAX_FXS_PATH,
address(this),
2105300114 // Expiration: a long time from now
);
return (amounts[0], amounts[1]);
}
// Burn unneeded or excess FRAX
function swapBurn(uint256 override_frax_amount, bool use_override) public onlyByOwnGov {
uint256 mintable_frax;
if (use_override){
// mintable_frax = override_USDC_amount.mul(10 ** missing_decimals).mul(COLLATERAL_RATIO_PRECISION).div(FRAX.global_collateral_ratio());
mintable_frax = override_frax_amount;
}
else {
mintable_frax = pool.buybackAvailableCollat();
}
(, uint256 fxs_received ) = _swapFRAXforFXS(mintable_frax);
// Calculate the amount to burn vs give to the yield distributor
uint256 amt_to_burn = fxs_received.mul(burn_fraction).div(PRICE_PRECISION);
uint256 amt_to_yield_distributor = fxs_received.sub(amt_to_burn);
// Burn some of the FXS
burnFXS(amt_to_burn);
// Give the rest to the yield distributor
FXS.approve(address(yieldDistributor), amt_to_yield_distributor);
yieldDistributor.notifyRewardAmount(amt_to_yield_distributor);
}
/* ========== Burns and givebacks ========== */
// Burn unneeded or excess FRAX. Goes through the minter
function burnFRAX(uint256 frax_amount) public onlyByOwnGovCust {
FRAX.approve(address(amo_minter), frax_amount);
amo_minter.burnFraxFromAMO(frax_amount);
}
// Burn unneeded FXS. Goes through the minter
function burnFXS(uint256 fxs_amount) public onlyByOwnGovCust {
FXS.approve(address(amo_minter), fxs_amount);
amo_minter.burnFxsFromAMO(fxs_amount);
}
/* ========== RESTRICTED GOVERNANCE FUNCTIONS ========== */
function setBurnFraction(uint256 _burn_fraction) external onlyByOwnGov {
burn_fraction = _burn_fraction;
}
function setFraxPool(address _frax_pool_address) external onlyByOwnGov {
pool = FraxPoolV3(_frax_pool_address);
}
function setAMOMinter(address _amo_minter_address) external onlyByOwnGov {
amo_minter = IFraxAMOMinter(_amo_minter_address);
// Get the timelock address from the minter
timelock_address = amo_minter.timelock_address();
// Make sure the new address is not address(0)
require(timelock_address != address(0), "Invalid timelock");
}
function setSafetyParams(uint256 _max_slippage) external onlyByOwnGov {
max_slippage = _max_slippage;
}
function setYieldDistributor(address _yield_distributor_address) external onlyByOwnGov {
yieldDistributor = veFXSYieldDistributorV4(_yield_distributor_address);
}
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov {
TransferHelper.safeTransfer(address(tokenAddress), msg.sender, tokenAmount);
}
// Generic proxy
function execute(
address _to,
uint256 _value,
bytes calldata _data
) external onlyByOwnGov returns (bool, bytes memory) {
(bool success, bytes memory result) = _to.call{value:_value}(_data);
return (success, result);
}
} | PRICE_PRECISION + missing decimals
| .div(10 ** (6 + missing_decimals[col_idx])); | 448,554 | [
1,
7698,
1441,
67,
3670,
26913,
397,
3315,
15105,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
18701,
263,
2892,
12,
2163,
2826,
261,
26,
397,
3315,
67,
31734,
63,
1293,
67,
3465,
5717,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xa22cf004eD5105608b39c48bE688BD9B9026a046/sources/FeePool.sol | * @notice Query whether an account has issued and has an outstanding debt balance @param account The address to query for/ | function hasIssued(address account)
external
view
returns (bool)
{
return issuanceData[account].initialDebtOwnership > 0;
}
event IssuanceRatioUpdated(uint newRatio);
| 4,057,280 | [
1,
1138,
2856,
392,
2236,
711,
16865,
471,
711,
392,
20974,
18202,
88,
11013,
225,
2236,
1021,
1758,
358,
843,
364,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
711,
7568,
5957,
12,
2867,
2236,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
327,
3385,
89,
1359,
751,
63,
4631,
8009,
6769,
758,
23602,
5460,
12565,
405,
374,
31,
203,
565,
289,
203,
203,
565,
871,
9310,
89,
1359,
8541,
7381,
12,
11890,
394,
8541,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.11;
contract Owned {
address public owner;
function Owned() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function setOwner(address _newOwner) onlyOwner {
owner = _newOwner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant 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 constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function toUINT112(uint256 a) internal constant returns(uint112) {
assert(uint112(a) == a);
return uint112(a);
}
function toUINT120(uint256 a) internal constant returns(uint120) {
assert(uint120(a) == a);
return uint120(a);
}
function toUINT128(uint256 a) internal constant returns(uint128) {
assert(uint128(a) == a);
return uint128(a);
}
}
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/issues/20
contract Token {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
//uint256 public totalSupply;
function totalSupply() constant returns (uint256 supply);
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/// VEN token, ERC20 compliant
contract VEN is Token, Owned {
using SafeMath for uint256;
string public constant name = "VeChain Token"; //The Token's name
uint8 public constant decimals = 18; //Number of decimals of the smallest unit
string public constant symbol = "VEN"; //An identifier
// packed to 256bit to save gas usage.
struct Supplies {
// uint128's max value is about 3e38.
// it's enough to present amount of tokens
uint128 total;
uint128 rawTokens;
}
Supplies supplies;
// Packed to 256bit to save gas usage.
struct Account {
// uint112's max value is about 5e33.
// it's enough to present amount of tokens
uint112 balance;
// raw token can be transformed into balance with bonus
uint112 rawTokens;
// safe to store timestamp
uint32 lastMintedTimestamp;
}
// Balances for each account
mapping(address => Account) accounts;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping(address => uint256)) allowed;
// bonus that can be shared by raw tokens
uint256 bonusOffered;
// Constructor
function VEN() {
}
function totalSupply() constant returns (uint256 supply){
return supplies.total;
}
// Send back ether sent to me
function () {
revert();
}
// If sealed, transfer is enabled and mint is disabled
function isSealed() constant returns (bool) {
return owner == 0;
}
function lastMintedTimestamp(address _owner) constant returns(uint32) {
return accounts[_owner].lastMintedTimestamp;
}
// Claim bonus by raw tokens
function claimBonus(address _owner) internal{
require(isSealed());
if (accounts[_owner].rawTokens != 0) {
uint256 realBalance = balanceOf(_owner);
uint256 bonus = realBalance
.sub(accounts[_owner].balance)
.sub(accounts[_owner].rawTokens);
accounts[_owner].balance = realBalance.toUINT112();
accounts[_owner].rawTokens = 0;
if(bonus > 0){
Transfer(this, _owner, bonus);
}
}
}
// What is the balance of a particular account?
function balanceOf(address _owner) constant returns (uint256 balance) {
if (accounts[_owner].rawTokens == 0)
return accounts[_owner].balance;
if (bonusOffered > 0) {
uint256 bonus = bonusOffered
.mul(accounts[_owner].rawTokens)
.div(supplies.rawTokens);
return bonus.add(accounts[_owner].balance)
.add(accounts[_owner].rawTokens);
}
return uint256(accounts[_owner].balance)
.add(accounts[_owner].rawTokens);
}
// Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _amount) returns (bool success) {
require(isSealed());
// implicitly claim bonus for both sender and receiver
claimBonus(msg.sender);
claimBonus(_to);
// according to VEN's total supply, never overflow here
if (accounts[msg.sender].balance >= _amount
&& _amount > 0) {
accounts[msg.sender].balance -= uint112(_amount);
accounts[_to].balance = _amount.add(accounts[_to].balance).toUINT112();
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
// Send _value amount of tokens from address _from to address _to
// The transferFrom method is used for a withdraw workflow, allowing contracts to send
// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
// fees in sub-currencies; the command should fail unless the _from account has
// deliberately authorized the sender of the message via some mechanism; we propose
// these standardized APIs for approval:
function transferFrom(
address _from,
address _to,
uint256 _amount
) returns (bool success) {
require(isSealed());
// implicitly claim bonus for both sender and receiver
claimBonus(_from);
claimBonus(_to);
// according to VEN's total supply, never overflow here
if (accounts[_from].balance >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0) {
accounts[_from].balance -= uint112(_amount);
allowed[_from][msg.sender] -= _amount;
accounts[_to].balance = _amount.add(accounts[_to].balance).toUINT112();
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _amount) returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
//if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { revert(); }
ApprovalReceiver(_spender).receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
// Mint tokens and assign to some one
function mint(address _owner, uint256 _amount, bool _isRaw, uint32 timestamp) onlyOwner{
if (_isRaw) {
accounts[_owner].rawTokens = _amount.add(accounts[_owner].rawTokens).toUINT112();
supplies.rawTokens = _amount.add(supplies.rawTokens).toUINT128();
} else {
accounts[_owner].balance = _amount.add(accounts[_owner].balance).toUINT112();
}
accounts[_owner].lastMintedTimestamp = timestamp;
supplies.total = _amount.add(supplies.total).toUINT128();
Transfer(0, _owner, _amount);
}
// Offer bonus to raw tokens holder
function offerBonus(uint256 _bonus) onlyOwner {
bonusOffered = bonusOffered.add(_bonus);
supplies.total = _bonus.add(supplies.total).toUINT128();
Transfer(0, this, _bonus);
}
// Set owner to zero address, to disable mint, and enable token transfer
function seal() onlyOwner {
setOwner(0);
}
}
contract ApprovalReceiver {
function receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData);
}
// Contract to sell and distribute VEN tokens
contract VENSale is Owned{
/// chart of stage transition
///
/// deploy initialize startTime endTime finalize
/// | <-earlyStageLasts-> | | <- closedStageLasts -> |
/// O-----------O---------------O---------------------O-------------O------------------------O------------>
/// Created Initialized Early Normal Closed Finalized
enum Stage {
NotCreated,
Created,
Initialized,
Early,
Normal,
Closed,
Finalized
}
using SafeMath for uint256;
uint256 public constant totalSupply = (10 ** 9) * (10 ** 18); // 1 billion VEN, decimals set to 18
uint256 constant privateSupply = totalSupply * 9 / 100; // 9% for private ICO
uint256 constant commercialPlan = totalSupply * 23 / 100; // 23% for commercial plan
uint256 constant reservedForTeam = totalSupply * 5 / 100; // 5% for team
uint256 constant reservedForOperations = totalSupply * 22 / 100; // 22 for operations
// 59%
uint256 public constant nonPublicSupply = privateSupply + commercialPlan + reservedForTeam + reservedForOperations;
// 41%
uint256 public constant publicSupply = totalSupply - nonPublicSupply;
uint256 public constant officialLimit = 64371825 * (10 ** 18);
uint256 public constant channelsLimit = publicSupply - officialLimit;
// packed to 256bit
struct SoldOut {
uint16 placeholder; // placeholder to make struct pre-alloced
// amount of tokens officially sold out.
// max value of 120bit is about 1e36, it's enough for token amount
uint120 official;
uint120 channels; // amount of tokens sold out via channels
}
SoldOut soldOut;
uint256 constant venPerEth = 3500; // normal exchange rate
uint256 constant venPerEthEarlyStage = venPerEth + venPerEth * 15 / 100; // early stage has 15% reward
uint constant minBuyInterval = 30 minutes; // each account can buy once in 30 minutes
uint constant maxBuyEthAmount = 30 ether;
VEN ven; // VEN token contract follows ERC20 standard
address ethVault; // the account to keep received ether
address venVault; // the account to keep non-public offered VEN tokens
uint public constant startTime = 1503057600; // time to start sale
uint public constant endTime = 1504180800; // tiem to close sale
uint public constant earlyStageLasts = 3 days; // early bird stage lasts in seconds
bool initialized;
bool finalized;
function VENSale() {
soldOut.placeholder = 1;
}
/// @notice calculte exchange rate according to current stage
/// @return exchange rate. zero if not in sale.
function exchangeRate() constant returns (uint256){
if (stage() == Stage.Early) {
return venPerEthEarlyStage;
}
if (stage() == Stage.Normal) {
return venPerEth;
}
return 0;
}
/// @notice for test purpose
function blockTime() constant returns (uint32) {
return uint32(block.timestamp);
}
/// @notice estimate stage
/// @return current stage
function stage() constant returns (Stage) {
if (finalized) {
return Stage.Finalized;
}
if (!initialized) {
// deployed but not initialized
return Stage.Created;
}
if (blockTime() < startTime) {
// not started yet
return Stage.Initialized;
}
if (uint256(soldOut.official).add(soldOut.channels) >= publicSupply) {
// all sold out
return Stage.Closed;
}
if (blockTime() < endTime) {
// in sale
if (blockTime() < startTime.add(earlyStageLasts)) {
// early bird stage
return Stage.Early;
}
// normal stage
return Stage.Normal;
}
// closed
return Stage.Closed;
}
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size > 0;
}
/// @notice entry to buy tokens
function () payable {
buy();
}
/// @notice entry to buy tokens
function buy() payable {
// reject contract buyer to avoid breaking interval limit
require(!isContract(msg.sender));
require(msg.value >= 0.01 ether);
uint256 rate = exchangeRate();
// here don't need to check stage. rate is only valid when in sale
require(rate > 0);
// each account is allowed once in minBuyInterval
require(blockTime() >= ven.lastMintedTimestamp(msg.sender) + minBuyInterval);
uint256 requested;
// and limited to maxBuyEthAmount
if (msg.value > maxBuyEthAmount) {
requested = maxBuyEthAmount.mul(rate);
} else {
requested = msg.value.mul(rate);
}
uint256 remained = officialLimit.sub(soldOut.official);
if (requested > remained) {
//exceed remained
requested = remained;
}
uint256 ethCost = requested.div(rate);
if (requested > 0) {
ven.mint(msg.sender, requested, true, blockTime());
// transfer ETH to vault
ethVault.transfer(ethCost);
soldOut.official = requested.add(soldOut.official).toUINT120();
onSold(msg.sender, requested, ethCost);
}
uint256 toReturn = msg.value.sub(ethCost);
if(toReturn > 0) {
// return over payed ETH
msg.sender.transfer(toReturn);
}
}
/// @notice returns tokens sold officially
function officialSold() constant returns (uint256) {
return soldOut.official;
}
/// @notice returns tokens sold via channels
function channelsSold() constant returns (uint256) {
return soldOut.channels;
}
/// @notice manually offer tokens to channel
function offerToChannel(address _channelAccount, uint256 _venAmount) onlyOwner {
Stage stg = stage();
// since the settlement may be delayed, so it's allowed in closed stage
require(stg == Stage.Early || stg == Stage.Normal || stg == Stage.Closed);
soldOut.channels = _venAmount.add(soldOut.channels).toUINT120();
//should not exceed limit
require(soldOut.channels <= channelsLimit);
ven.mint(
_channelAccount,
_venAmount,
true, // unsold tokens can be claimed by channels portion
blockTime()
);
onSold(_channelAccount, _venAmount, 0);
}
/// @notice initialize to prepare for sale
/// @param _ven The address VEN token contract following ERC20 standard
/// @param _ethVault The place to store received ETH
/// @param _venVault The place to store non-publicly supplied VEN tokens
function initialize(
VEN _ven,
address _ethVault,
address _venVault) onlyOwner {
require(stage() == Stage.Created);
// ownership of token contract should already be this
require(_ven.owner() == address(this));
require(address(_ethVault) != 0);
require(address(_venVault) != 0);
ven = _ven;
ethVault = _ethVault;
venVault = _venVault;
ven.mint(
venVault,
reservedForTeam.add(reservedForOperations),
false, // team and operations reserved portion can't share unsold tokens
blockTime()
);
ven.mint(
venVault,
privateSupply.add(commercialPlan),
true, // private ICO and commercial plan can share unsold tokens
blockTime()
);
initialized = true;
onInitialized();
}
/// @notice finalize
function finalize() onlyOwner {
// only after closed stage
require(stage() == Stage.Closed);
uint256 unsold = publicSupply.sub(soldOut.official).sub(soldOut.channels);
if (unsold > 0) {
// unsold VEN as bonus
ven.offerBonus(unsold);
}
ven.seal();
finalized = true;
onFinalized();
}
event onInitialized();
event onFinalized();
event onSold(address indexed buyer, uint256 venAmount, uint256 ethCost);
} | @notice initialize to prepare for sale @param _ven The address VEN token contract following ERC20 standard @param _ethVault The place to store received ETH @param _venVault The place to store non-publicly supplied VEN tokens ownership of token contract should already be this | function initialize(
VEN _ven,
address _ethVault,
address _venVault) onlyOwner {
require(stage() == Stage.Created);
require(_ven.owner() == address(this));
require(address(_ethVault) != 0);
require(address(_venVault) != 0);
ven = _ven;
ethVault = _ethVault;
venVault = _venVault;
ven.mint(
venVault,
reservedForTeam.add(reservedForOperations),
blockTime()
);
ven.mint(
venVault,
privateSupply.add(commercialPlan),
blockTime()
);
initialized = true;
onInitialized();
}
| 7,214,581 | [
1,
11160,
358,
2911,
364,
272,
5349,
225,
389,
3995,
1021,
1758,
776,
1157,
1147,
6835,
3751,
4232,
39,
3462,
4529,
225,
389,
546,
12003,
1021,
3166,
358,
1707,
5079,
512,
2455,
225,
389,
3995,
12003,
1021,
3166,
358,
1707,
1661,
17,
482,
715,
4580,
776,
1157,
2430,
23178,
434,
1147,
6835,
1410,
1818,
506,
333,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
4046,
12,
203,
3639,
776,
1157,
389,
3995,
16,
203,
3639,
1758,
389,
546,
12003,
16,
203,
3639,
1758,
389,
3995,
12003,
13,
1338,
5541,
288,
203,
3639,
2583,
12,
12869,
1435,
422,
16531,
18,
6119,
1769,
203,
203,
3639,
2583,
24899,
3995,
18,
8443,
1435,
422,
1758,
12,
2211,
10019,
203,
203,
3639,
2583,
12,
2867,
24899,
546,
12003,
13,
480,
374,
1769,
203,
3639,
2583,
12,
2867,
24899,
3995,
12003,
13,
480,
374,
1769,
4202,
203,
203,
3639,
331,
275,
273,
389,
3995,
31,
203,
540,
203,
3639,
13750,
12003,
273,
389,
546,
12003,
31,
203,
3639,
331,
275,
12003,
273,
389,
3995,
12003,
31,
377,
203,
540,
203,
3639,
331,
275,
18,
81,
474,
12,
203,
5411,
331,
275,
12003,
16,
203,
5411,
8735,
1290,
8689,
18,
1289,
12,
18898,
1290,
9343,
3631,
203,
5411,
1203,
950,
1435,
203,
3639,
11272,
203,
203,
3639,
331,
275,
18,
81,
474,
12,
203,
5411,
331,
275,
12003,
16,
203,
5411,
3238,
3088,
1283,
18,
1289,
12,
5702,
12610,
649,
5365,
3631,
203,
5411,
1203,
950,
1435,
203,
3639,
11272,
203,
203,
3639,
6454,
273,
638,
31,
203,
3639,
603,
11459,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x4b21da40Dd8d9F4363e69A9a1620D7cdb49123be/sources/StakingPools.sol | @dev modifier add referral to referrallist. Users are indexed in order to keep track of | modifier checkIfNewReferral(uint256 pid, address referral) {
Pool.Data storage _pool = _pools.get(pid);
if (_pool.onReferralBonus && referral != address(0)) {
if (!referralIsKnown[referral][pid]) {
referralList[pid][nextReferral[pid]] = referral;
referralIsKnown[referral][pid] = true;
nextReferral[pid]++;
emit NewReferralAdded(referral, msg.sender);
}
address refereeAddr = msg.sender;
address[] storage referees = myreferees[pid][referral];
for (uint256 i = 0; i < referees.length; i++) {
if (referees[i] == refereeAddr) {
toAdd = false;
}
}
if (toAdd) {
referees.push(refereeAddr);
}
}
_;
}
| 2,757,027 | [
1,
20597,
527,
1278,
29084,
358,
1278,
370,
454,
376,
18,
12109,
854,
8808,
316,
1353,
358,
3455,
3298,
434,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
9606,
19130,
1908,
1957,
29084,
12,
11890,
5034,
4231,
16,
1758,
1278,
29084,
13,
288,
203,
565,
8828,
18,
751,
2502,
389,
6011,
273,
389,
27663,
18,
588,
12,
6610,
1769,
203,
203,
565,
309,
261,
67,
6011,
18,
265,
1957,
29084,
38,
22889,
597,
1278,
29084,
480,
1758,
12,
20,
3719,
288,
203,
1377,
309,
16051,
1734,
29084,
2520,
11925,
63,
1734,
29084,
6362,
6610,
5717,
288,
203,
1850,
1278,
29084,
682,
63,
6610,
6362,
4285,
1957,
29084,
63,
6610,
13563,
273,
1278,
29084,
31,
203,
1850,
1278,
29084,
2520,
11925,
63,
1734,
29084,
6362,
6610,
65,
273,
638,
31,
203,
1850,
1024,
1957,
29084,
63,
6610,
3737,
15,
31,
203,
203,
1850,
3626,
1166,
1957,
29084,
8602,
12,
1734,
29084,
16,
1234,
18,
15330,
1769,
203,
1377,
289,
203,
203,
1377,
1758,
8884,
1340,
3178,
273,
1234,
18,
15330,
31,
203,
1377,
1758,
8526,
2502,
225,
8884,
25521,
273,
3399,
266,
586,
25521,
63,
6610,
6362,
1734,
29084,
15533,
203,
1377,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
8884,
25521,
18,
2469,
31,
277,
27245,
288,
203,
3639,
309,
261,
266,
586,
25521,
63,
77,
65,
422,
8884,
1340,
3178,
13,
288,
203,
1850,
25607,
273,
629,
31,
203,
3639,
289,
203,
1377,
289,
203,
203,
1377,
309,
261,
869,
986,
13,
288,
203,
3639,
8884,
25521,
18,
6206,
12,
266,
586,
1340,
3178,
1769,
203,
1377,
289,
203,
565,
289,
7010,
203,
565,
389,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
//
// Our shop contract acts as a payment provider for our in-game shop system.
// Coin packages that are purchased here are being picked up by our offchain
// sync network and are then translated into in-game assets. This happens with
// minimal delay and enables a fluid gameplay experience. An in-game notification
// informs players about the successful purchase of coins.
//
// Prices are scaled against the current USD value of ETH courtesy of
// MAKERDAO (https://developer.makerdao.com/feeds/)
// This enables us to match our native In-App-Purchase prices from e.g. Apple's AppStore
// We can also reduce the price of packages temporarily for e.g. events and promotions.
//
pragma solidity ^0.4.21;
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) constant returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
function DSAuth() {
owner = msg.sender;
LogSetOwner(msg.sender);
}
function setOwner(address owner_)
auth
{
owner = owner_;
LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
auth
{
authority = authority_;
LogSetAuthority(authority);
}
modifier auth {
assert(isAuthorized(msg.sender, msg.sig));
_;
}
modifier authorized(bytes4 sig) {
assert(isAuthorized(msg.sender, sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, this, sig);
}
}
function assert(bool x) internal {
if (!x) throw;
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
contract DSMath {
/*
standard uint256 functions
*/
function add(uint256 x, uint256 y) constant internal returns (uint256 z) {
assert((z = x + y) >= x);
}
function sub(uint256 x, uint256 y) constant internal returns (uint256 z) {
assert((z = x - y) <= x);
}
function mul(uint256 x, uint256 y) constant internal returns (uint256 z) {
assert((z = x * y) >= x);
}
function div(uint256 x, uint256 y) constant internal returns (uint256 z) {
z = x / y;
}
function min(uint256 x, uint256 y) constant internal returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) constant internal returns (uint256 z) {
return x >= y ? x : y;
}
/*
uint128 functions (h is for half)
*/
function hadd(uint128 x, uint128 y) constant internal returns (uint128 z) {
assert((z = x + y) >= x);
}
function hsub(uint128 x, uint128 y) constant internal returns (uint128 z) {
assert((z = x - y) <= x);
}
function hmul(uint128 x, uint128 y) constant internal returns (uint128 z) {
assert((z = x * y) >= x);
}
function hdiv(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = x / y;
}
function hmin(uint128 x, uint128 y) constant internal returns (uint128 z) {
return x <= y ? x : y;
}
function hmax(uint128 x, uint128 y) constant internal returns (uint128 z) {
return x >= y ? x : y;
}
/*
int256 functions
*/
function imin(int256 x, int256 y) constant internal returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) constant internal returns (int256 z) {
return x >= y ? x : y;
}
/*
WAD math
*/
uint128 constant WAD = 10 ** 18;
function wadd(uint128 x, uint128 y) constant internal returns (uint128) {
return hadd(x, y);
}
function wsub(uint128 x, uint128 y) constant internal returns (uint128) {
return hsub(x, y);
}
function wmul(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * y + WAD / 2) / WAD);
}
function wdiv(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * WAD + y / 2) / y);
}
function wmin(uint128 x, uint128 y) constant internal returns (uint128) {
return hmin(x, y);
}
function wmax(uint128 x, uint128 y) constant internal returns (uint128) {
return hmax(x, y);
}
/*
RAY math
*/
uint128 constant RAY = 10 ** 27;
function radd(uint128 x, uint128 y) constant internal returns (uint128) {
return hadd(x, y);
}
function rsub(uint128 x, uint128 y) constant internal returns (uint128) {
return hsub(x, y);
}
function rmul(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * y + RAY / 2) / RAY);
}
function rdiv(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * RAY + y / 2) / y);
}
function rpow(uint128 x, uint64 n) constant internal returns (uint128 z) {
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
function rmin(uint128 x, uint128 y) constant internal returns (uint128) {
return hmin(x, y);
}
function rmax(uint128 x, uint128 y) constant internal returns (uint128) {
return hmax(x, y);
}
function cast(uint256 x) constant internal returns (uint128 z) {
assert((z = uint128(x)) == x);
}
}
contract DSThing is DSAuth, DSNote, DSMath {
}
contract DSValue is DSThing {
bool has;
bytes32 val;
function peek() constant returns (bytes32, bool) {
return (val,has);
}
function read() constant returns (bytes32) {
var (wut, has) = peek();
assert(has);
return wut;
}
function poke(bytes32 wut) note auth {
val = wut;
has = true;
}
function void() note auth { // unset the value
has = false;
}
}
contract Medianizer is DSValue {
mapping (bytes12 => address) public values;
mapping (address => bytes12) public indexes;
bytes12 public next = 0x1;
uint96 public min = 0x1;
function set(address wat) auth {
bytes12 nextId = bytes12(uint96(next) + 1);
assert(nextId != 0x0);
set(next, wat);
next = nextId;
}
function set(bytes12 pos, address wat) note auth {
if (pos == 0x0) throw;
if (wat != 0 && indexes[wat] != 0) throw;
indexes[values[pos]] = 0; // Making sure to remove a possible existing address in that position
if (wat != 0) {
indexes[wat] = pos;
}
values[pos] = wat;
}
function setMin(uint96 min_) note auth {
if (min_ == 0x0) throw;
min = min_;
}
function setNext(bytes12 next_) note auth {
if (next_ == 0x0) throw;
next = next_;
}
function unset(bytes12 pos) {
set(pos, 0);
}
function unset(address wat) {
set(indexes[wat], 0);
}
function poke() {
poke(0);
}
function poke(bytes32) note {
(val, has) = compute();
}
function compute() constant returns (bytes32, bool) {
bytes32[] memory wuts = new bytes32[](uint96(next) - 1);
uint96 ctr = 0;
for (uint96 i = 1; i < uint96(next); i++) {
if (values[bytes12(i)] != 0) {
var (wut, wuz) = DSValue(values[bytes12(i)]).peek();
if (wuz) {
if (ctr == 0 || wut >= wuts[ctr - 1]) {
wuts[ctr] = wut;
} else {
uint96 j = 0;
while (wut >= wuts[j]) {
j++;
}
for (uint96 k = ctr; k > j; k--) {
wuts[k] = wuts[k - 1];
}
wuts[j] = wut;
}
ctr++;
}
}
}
if (ctr < min) return (val, false);
bytes32 value;
if (ctr % 2 == 0) {
uint128 val1 = uint128(wuts[(ctr / 2) - 1]);
uint128 val2 = uint128(wuts[ctr / 2]);
value = bytes32(wdiv(hadd(val1, val2), 2 ether));
} else {
value = wuts[(ctr - 1) / 2];
}
return (value, true);
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
* via OpenZeppelin
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0));
OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract ChainmonstersMedianizer is Ownable {
address medianizerBase;
Medianizer makerMed;
constructor(address _medianizerContract) public {
owner = msg.sender;
medianizerBase = _medianizerContract;
makerMed = Medianizer(medianizerBase);
}
function updateMedianizerBase(address _medianizerContract) public onlyOwner {
medianizerBase = _medianizerContract;
makerMed = Medianizer(medianizerBase);
}
function getUSDPrice() public view returns (uint256) {
return bytesToUint(toBytes(makerMed.read()));
}
function isMedianizer() public view returns (bool) {
return true;
}
function toBytes(bytes32 _data) public pure returns (bytes) {
return abi.encodePacked(_data);
}
function bytesToUint(bytes b) public pure returns (uint256){
uint256 number;
for(uint i=0;i<b.length;i++){
number = number + uint(b[i])*(2**(8*(b.length-(i+1))));
}
return number;
}
}
/**
* @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) {
if (a == 0) {
return 0;
}
uint256 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 c;
}
/**
* @dev Substracts two numbers, returns 0 if it would go into minus range.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
if (b >= a) {
return 0;
}
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ChainmonstersShop {
using SafeMath for uint256;
// static
address public owner;
// start auction manually at given time
bool started;
uint256 public totalCoinsSold;
address medianizer;
uint256 shiftValue = 100; // double digit shifting to support prices like $29.99
uint256 multiplier = 10000; // internal multiplier
struct Package {
// price in USD
uint256 price;
// reference to in-game equivalent e.g. "100 Coins"
string packageReference;
// available for purchase?
bool isActive;
// amount of coins
uint256 coinsAmount;
}
event LogPurchase(address _from, uint256 _price, string _packageReference);
mapping(address => uint256) public addressToCoinsPurchased;
Package[] packages;
constructor() public {
owner = msg.sender;
started = false;
}
function startShop() public onlyOwner {
require(started == false);
}
// in case of contract switch or adding new packages
function pauseShop() public onlyOwner {
require(started == true);
}
function isStarted() public view returns (bool success) {
return started;
}
function purchasePackage(uint256 _id) public
payable
returns (bool success)
{
require(started == true);
require(packages[_id].isActive == true);
require(msg.sender != owner);
require(msg.value == priceOf(packages[_id].price)); // only accept 100% accurate prices
addressToCoinsPurchased[msg.sender] += packages[_id].coinsAmount;
totalCoinsSold += packages[_id].coinsAmount;
emit LogPurchase(msg.sender, msg.value, packages[_id].packageReference);
}
function addPackage(uint256 _price, string _packageReference, bool _isActive, uint256 _coinsAmount)
external
onlyOwner
{
require(_price > 0);
Package memory _package = Package({
price: uint256(_price),
packageReference: string(_packageReference),
isActive: bool(_isActive),
coinsAmount: uint256(_coinsAmount)
});
uint256 newPackageId = packages.push(_package);
}
function setPrice(uint256 _packageId, uint256 _newPrice)
external
onlyOwner
{
require(packages[_packageId].price > 0);
packages[_packageId].price = _newPrice;
}
function getPackage(uint256 _id)
external
view
returns (uint256 priceInETH, uint256 priceInUSD, string packageReference, uint256 coinsAmount )
{
Package storage package = packages[_id];
priceInETH = priceOf(_id);
priceInUSD = package.price;
packageReference = package.packageReference;
coinsAmount = package.coinsAmount;
}
function priceOf(uint256 _packageId)
public
view
returns (uint256)
{
// if no medianizer is set then return fixed price(!)
if (medianizer == address(0x0)) {
return packages[_packageId].price;
}
else {
// the price of usd/eth gets returned from medianizer
uint256 USDinWei = ChainmonstersMedianizer(medianizer).getUSDPrice();
uint256 multValue = (packages[_packageId].price.mul(multiplier)).div(USDinWei.div(1 ether));
uint256 inWei = multValue.mul(1 ether);
uint256 result = inWei.div(shiftValue.mul(multiplier));
return result;
}
}
function getPackagesCount()
public
view
returns (uint256)
{
return packages.length;
}
function setMedianizer(ChainmonstersMedianizer _medianizer)
public
onlyOwner
{
require(_medianizer.isMedianizer(), "given address is not a medianizer contract!");
medianizer = _medianizer;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
} | double digit shifting to support prices like $29.99
| uint256 shiftValue = 100; | 5,448,358 | [
1,
9056,
8035,
699,
430,
1787,
358,
2865,
19827,
3007,
271,
5540,
18,
2733,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2254,
5034,
4654,
620,
273,
2130,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// 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-upgradeable/proxy/Initializable.sol
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-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 || _isConstructor() || !_initialized, "Initializable: contract is already 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) {
return !AddressUpgradeable.isContract(address(this));
}
}
// File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.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 ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
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;
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol
pragma solidity >=0.6.0 <0.8.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;
}
// File: @openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @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-upgradeable/math/SafeMathUpgradeable.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 SafeMathUpgradeable {
/**
* @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-upgradeable/token/ERC20/SafeERC20Upgradeable.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 SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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/introspection/IERC165.sol
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: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// File: contracts/interfaces/IMintableCollection.sol
pragma solidity 0.6.12;
interface IMintableCollection is IERC721 {
function burn(uint256 tokenId) external;
function mint(address to, uint256 tokenId) external;
}
// File: contracts/interfaces/IRewardable.sol
pragma solidity 0.6.12;
interface IRewardable {
function addRewards(address rewardToken, uint256 amount) external;
}
// File: @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.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 OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
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;
}
uint256[49] private __gap;
}
// File: contracts/abstract/EmergencyWithdrawable.sol
pragma solidity 0.6.12;
abstract contract EmergencyWithdrawable is OwnableUpgradeable {
// for worst case scenarios or to recover funds from people sending to this contract by mistake
function emergencyWithdrawETH() external payable onlyOwner {
msg.sender.send(address(this).balance);
}
// for worst case scenarios or to recover funds from people sending to this contract by mistake
function emergencyWithdrawTokens(IERC20Upgradeable token) external onlyOwner {
token.transfer(msg.sender, token.balanceOf(address(this)));
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
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/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);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @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/AccessControl.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _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 {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// File: @openzeppelin/contracts/introspection/ERC165.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract 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 virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: @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, 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/EnumerableMap.sol
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: @openzeppelin/contracts/utils/Strings.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @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 _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));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, 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 virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.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 _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {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);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// File: contracts/UnicStakingERC721.sol
pragma solidity 0.6.12;
contract UnicStakingERC721 is AccessControl, ERC721, IMintableCollection {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
constructor(
string memory name,
string memory symbol,
string memory baseURI
) public ERC721(name, symbol) {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
}
function burn(uint256 tokenId) public override virtual {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"UnicStakingERC721: caller is not owner nor approved"
);
_burn(tokenId);
}
function setBaseURI(string memory baseURI) public {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"UnicStakingERC721: must have admin role to change baseUri"
);
_setBaseURI(baseURI);
}
function mint(address to, uint256 tokenId) public override virtual {
require(
hasRole(MINTER_ROLE, _msgSender()),
"UnicStakingERC721: must have minter role to mint"
);
_mint(to, tokenId);
}
}
// File: contracts/interfaces/IUnicFactory.sol
pragma solidity >=0.5.0;
interface IUnicFactory {
event TokenCreated(address indexed caller, address indexed uToken);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getUToken(address uToken) external view returns (uint);
function uTokens(uint) external view returns (address);
function uTokensLength() external view returns (uint);
function createUToken(uint256 totalSupply, uint8 decimals, string calldata name, string calldata symbol, uint256 threshold, string calldata description) external returns (address);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// File: contracts/UnicStakingV4.sol
pragma solidity 0.6.12;
// This upgrade adds a getter/setter for the stakingToken + adds some emergency withdraw utilities
contract UnicStakingV4 is Initializable, EmergencyWithdrawable, IRewardable, PausableUpgradeable {
using SafeMath for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
struct StakerInfo {
uint256 nftId;
uint256 amount;
uint256 stakeStartTime;
uint256 lockDays;
uint256 rewardDebt;
address rewardToken;
uint16 multiplier;
}
struct LockMultiplier {
uint16 multiplier;
bool exists;
}
struct RewardPool {
IERC20Upgradeable rewardToken;
uint256 stakedAmount;
uint256 stakedAmountWithMultipliers;
uint256 totalRewardAmount;
uint256 accRewardPerShare;
uint256 lastRewardAmount;
}
IERC20Upgradeable private stakingToken;
IMintableCollection private nftCollection;
uint256 public minStakeAmount;
uint256 private nftStartId;
// NFT ID to staker info
mapping(uint256 => StakerInfo) public stakes;
// Each uToken should have its own poolcontracts/UnicStaking.sol:115:9
mapping(address => RewardPool) public pools;
// Mapping from days => multiplier for timelock
mapping(uint256 => LockMultiplier) public lockMultipliers;
uint256 private constant DIV_PRECISION = 1e18;
event AddRewards(address indexed rewardToken, uint256 amount);
event Staked(
address indexed account,
address indexed rewardToken,
uint256 nftId,
uint256 amount,
uint256 lockDays
);
event Harvest(address indexed staker, address indexed rewardToken, uint256 nftId, uint256 amount);
event Withdraw(address indexed staker, address indexed rewardToken, uint256 nftId, uint256 amount);
event LogUpdateRewards(address indexed rewardToken, uint256 totalRewards, uint256 accRewardPerShare);
modifier poolExists(address rewardToken) {
require(address(pools[rewardToken].rewardToken) != address(0), "UnicStaking: Pool does not exist");
_;
}
modifier poolNotExists(address rewardToken) {
require(address(pools[rewardToken].rewardToken) == address(0), "UnicStaking: Pool does already exist");
_;
}
IUnicFactory private factory;
function initialize(
IERC20Upgradeable _stakingToken,
IMintableCollection _nftCollection,
uint256 _nftStartId,
uint256 _minStakeAmount
) public initializer {
__Ownable_init();
stakingToken = _stakingToken;
nftCollection = _nftCollection;
nftStartId = _nftStartId;
minStakeAmount = _minStakeAmount;
}
function setUnicFactory(IUnicFactory _factory) external onlyOwner {
factory = _factory;
}
// lockdays are passed as seconds, multiplier in percentage from 100 (e.g. 170 for 70% on top)
function setLockMultiplier(uint256 lockDays, uint16 multiplier) external onlyOwner {
require(multiplier >= 100, "Minimum multiplier = 100");
lockMultipliers[lockDays] = LockMultiplier({
multiplier: multiplier,
exists: true
});
}
// lockdays are passed as seconds
function deleteLockMultiplier(uint256 lockDays) external onlyOwner {
delete lockMultipliers[lockDays];
}
function setMinStakeAmount(uint256 _minStakeAmount) external onlyOwner {
minStakeAmount = _minStakeAmount;
}
function setNftStartId(uint256 _nftStartId) external onlyOwner {
nftStartId = _nftStartId;
}
/**
* @param amount Amount of staking tokens
* @param lockDays How many days the staker wants to lock
* @param rewardToken The desired reward token to stake the tokens for (most likely a certain uToken)
*/
function stake(uint256 amount, uint256 lockDays, address rewardToken)
external
whenNotPaused
poolExists(rewardToken)
{
require(
amount >= minStakeAmount,
"UnicStaking: Amount must be greater than or equal to min stake amount"
);
require(
lockMultipliers[lockDays].exists,
"UnicStaking: Invalid number of lock days specified"
);
updateRewards(rewardToken);
// transfer the staking tokens into the staking pool
stakingToken.safeTransferFrom(msg.sender, address(this), amount);
// now the data of the staker is persisted
StakerInfo storage staker = stakes[nftStartId];
staker.stakeStartTime = block.timestamp;
staker.amount = amount;
staker.lockDays = lockDays;
staker.multiplier = lockMultipliers[lockDays].multiplier;
staker.nftId = nftStartId;
staker.rewardToken = rewardToken;
RewardPool storage pool = pools[rewardToken];
// the amount with lock multiplier applied
uint256 virtualAmount = virtualAmount(staker.amount, staker.multiplier);
staker.rewardDebt = virtualAmount.mul(pool.accRewardPerShare).div(DIV_PRECISION);
pool.stakedAmount = pool.stakedAmount.add(amount);
pool.stakedAmountWithMultipliers = pool.stakedAmountWithMultipliers.add(virtualAmount);
nftStartId = nftStartId.add(1);
nftCollection.mint(msg.sender, nftStartId - 1);
emit Staked(msg.sender, rewardToken, nftStartId - 1, amount, lockDays);
}
function withdraw(uint256 nftId) external whenNotPaused {
StakerInfo storage staker = stakes[nftId];
require(address(staker.rewardToken) != address(0), "UnicStaking: No staker exists");
require(
nftCollection.ownerOf(nftId) == msg.sender,
"UnicStaking: Only the owner may withdraw"
);
require(
(staker.stakeStartTime.add(staker.lockDays)) < block.timestamp,
"UnicStaking: Lock time not expired"
);
updateRewards(staker.rewardToken);
RewardPool storage pool = pools[address(staker.rewardToken)];
require(address(pool.rewardToken) != address(0), "UnicStaking: Pool gone");
// lets burn the NFT first
nftCollection.burn(nftId);
uint256 virtualAmount = virtualAmount(staker.amount, staker.multiplier);
uint256 accumulated = virtualAmount.mul(pool.accRewardPerShare).div(DIV_PRECISION);
uint256 reward = accumulated.sub(staker.rewardDebt);
// reset the pool props
pool.stakedAmount = pool.stakedAmount.sub(staker.amount);
pool.stakedAmountWithMultipliers = pool.stakedAmountWithMultipliers.sub(virtualAmount);
uint256 staked = staker.amount;
// reset all staker props
staker.rewardDebt = 0;
staker.amount = 0;
staker.stakeStartTime = 0;
staker.lockDays = 0;
staker.nftId = 0;
staker.rewardToken = address(0);
stakingToken.safeTransfer(msg.sender, reward.add(staked));
emit Harvest(msg.sender, address(staker.rewardToken), nftId, reward);
emit Withdraw(msg.sender, address(staker.rewardToken), nftId, staked);
}
function updateRewards(address rewardToken) private poolExists(rewardToken) {
RewardPool storage pool = pools[rewardToken];
require(address(pool.rewardToken) != address(0), "UnicStaking: Pool gone");
if (pool.totalRewardAmount > pool.lastRewardAmount) {
if (pool.stakedAmountWithMultipliers > 0) {
uint256 reward = pool.totalRewardAmount.sub(pool.lastRewardAmount);
pool.accRewardPerShare = pool.accRewardPerShare.add(reward.mul(DIV_PRECISION).div(pool.stakedAmountWithMultipliers));
}
pool.lastRewardAmount = pool.totalRewardAmount;
emit LogUpdateRewards(rewardToken, pool.lastRewardAmount, pool.accRewardPerShare);
}
}
function createPool(address rewardToken) external poolNotExists(rewardToken) {
require(
rewardToken == 0x94E0BAb2F6Ab1F19F4750E42d7349f2740513aD5 || // UNIC
rewardToken == 0x3d9233F15BB93C78a4f07B5C5F7A018630217cB3 || // first uToken (Unicly Genesis uUNICLY)
factory.getUToken(rewardToken) > 0,
"UnicStakingV2: rewardToken must be UNIC or uToken"
);
RewardPool memory pool = RewardPool({
rewardToken: IERC20Upgradeable(rewardToken),
stakedAmount: 0,
stakedAmountWithMultipliers: 0,
totalRewardAmount: 0,
accRewardPerShare: 0,
lastRewardAmount: 0
});
pools[rewardToken] = pool;
}
function addRewards(address rewardToken, uint256 amount) override external poolExists(rewardToken) {
require(amount > 0, "UnicStaking: Amount must be greater than zero");
IERC20Upgradeable(rewardToken).safeTransferFrom(msg.sender, address(this), amount);
RewardPool storage pool = pools[rewardToken];
pool.totalRewardAmount = pool.totalRewardAmount.add(amount);
emit AddRewards(rewardToken, amount);
}
function harvest(uint256 nftId) external whenNotPaused {
StakerInfo storage staker = stakes[nftId];
require(staker.nftId > 0, "UnicStaking: No staker exists");
require(
nftCollection.ownerOf(nftId) == msg.sender,
"UnicStaking: Only the owner may harvest"
);
updateRewards(address(staker.rewardToken));
RewardPool memory pool = pools[address(staker.rewardToken)];
uint256 accumulated = virtualAmount(staker.amount, staker.multiplier).mul(pool.accRewardPerShare).div(DIV_PRECISION);
uint256 reward;
// this needs to be considered due to roundings in reward calculation
if (accumulated > staker.rewardDebt) {
reward = accumulated.sub(staker.rewardDebt);
}
staker.rewardDebt = accumulated;
pool.rewardToken.safeTransfer(msg.sender, reward);
emit Harvest(msg.sender, address(staker.rewardToken), nftId, reward);
}
function pendingReward(uint256 nftId) external view returns (uint256) {
StakerInfo memory staker = stakes[nftId];
require(staker.nftId > 0, "StakingPool: No staker exists");
RewardPool memory pool = pools[address(staker.rewardToken)];
require(address(pool.rewardToken) != address(0), "UnicStaking: Pool gone");
uint256 accRewardPerShare = 0;
// run a part from the updateRewards logic but don't persist anything
if (pool.totalRewardAmount > pool.lastRewardAmount) {
if (pool.stakedAmountWithMultipliers > 0) {
uint256 reward = pool.totalRewardAmount.sub(pool.lastRewardAmount);
accRewardPerShare = pool.accRewardPerShare.add(reward.mul(DIV_PRECISION).div(pool.stakedAmountWithMultipliers));
}
}
uint256 accumulated = virtualAmount(staker.amount, staker.multiplier).mul(accRewardPerShare).div(DIV_PRECISION);
// this can happen due to roundings in the reward calculation
if (staker.rewardDebt > accumulated) {
return 0;
}
return accumulated.sub(staker.rewardDebt);
}
// returns the virtual amount after having a multiplier applied
function virtualAmount(uint256 amount, uint256 multiplier) private view returns (uint256) {
return amount.mul(multiplier.mul(DIV_PRECISION).div(100)).div(DIV_PRECISION);
}
// returns the stake with multiplier for an nftId
function getStakeWithMultiplier(uint256 nftId) external view returns (uint256 stakeWithMultiplier){
StakerInfo memory staker = stakes[nftId];
stakeWithMultiplier = virtualAmount(staker.amount, staker.multiplier);
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function getStakingToken() external view returns (address) {
return address(stakingToken);
}
// The initial deployment was done using UNIC as the staking token. We actually want to use xUNIC. That's why we
// needed to add this setter.
function setStakingToken(IERC20Upgradeable _stakingToken) external onlyOwner {
stakingToken = _stakingToken;
}
// See doc of `setStakingToken`. This allows an emergency withdrawal of staked UNIC.
function emergencyWithdrawStakes(uint256 nftId, address receiver) external onlyOwner {
StakerInfo storage staker = stakes[nftId];
require(staker.nftId > 0, "UnicStaking: No staker exists");
updateRewards(staker.rewardToken);
RewardPool storage pool = pools[address(staker.rewardToken)];
require(address(pool.rewardToken) != address(0), "UnicStaking: Pool gone");
uint256 virtualAmount = virtualAmount(staker.amount, staker.multiplier);
uint256 accumulated = virtualAmount.mul(pool.accRewardPerShare).div(DIV_PRECISION);
uint256 reward = accumulated.sub(staker.rewardDebt);
// reset the pool props
pool.stakedAmount = pool.stakedAmount.sub(staker.amount);
pool.stakedAmountWithMultipliers = pool.stakedAmountWithMultipliers.sub(virtualAmount);
uint256 staked = staker.amount;
// reset all staker props
staker.rewardDebt = 0;
staker.amount = 0;
staker.stakeStartTime = 0;
staker.lockDays = 0;
staker.nftId = 0;
staker.rewardToken = address(0);
stakingToken.safeTransfer(receiver, reward.add(staked));
emit Harvest(receiver, address(staker.rewardToken), nftId, reward);
emit Withdraw(receiver, address(staker.rewardToken), nftId, staked);
}
} | lets burn the NFT first reset the pool props reset all staker props | function withdraw(uint256 nftId) external whenNotPaused {
StakerInfo storage staker = stakes[nftId];
require(address(staker.rewardToken) != address(0), "UnicStaking: No staker exists");
require(
nftCollection.ownerOf(nftId) == msg.sender,
"UnicStaking: Only the owner may withdraw"
);
require(
(staker.stakeStartTime.add(staker.lockDays)) < block.timestamp,
"UnicStaking: Lock time not expired"
);
updateRewards(staker.rewardToken);
RewardPool storage pool = pools[address(staker.rewardToken)];
require(address(pool.rewardToken) != address(0), "UnicStaking: Pool gone");
nftCollection.burn(nftId);
uint256 virtualAmount = virtualAmount(staker.amount, staker.multiplier);
uint256 accumulated = virtualAmount.mul(pool.accRewardPerShare).div(DIV_PRECISION);
uint256 reward = accumulated.sub(staker.rewardDebt);
pool.stakedAmount = pool.stakedAmount.sub(staker.amount);
pool.stakedAmountWithMultipliers = pool.stakedAmountWithMultipliers.sub(virtualAmount);
uint256 staked = staker.amount;
staker.rewardDebt = 0;
staker.amount = 0;
staker.stakeStartTime = 0;
staker.lockDays = 0;
staker.nftId = 0;
staker.rewardToken = address(0);
stakingToken.safeTransfer(msg.sender, reward.add(staked));
emit Harvest(msg.sender, address(staker.rewardToken), nftId, reward);
emit Withdraw(msg.sender, address(staker.rewardToken), nftId, staked);
}
| 380,226 | [
1,
17307,
18305,
326,
423,
4464,
1122,
2715,
326,
2845,
3458,
2715,
777,
384,
6388,
3458,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
598,
9446,
12,
11890,
5034,
290,
1222,
548,
13,
3903,
1347,
1248,
28590,
288,
203,
3639,
934,
6388,
966,
2502,
384,
6388,
273,
384,
3223,
63,
82,
1222,
548,
15533,
203,
3639,
2583,
12,
2867,
12,
334,
6388,
18,
266,
2913,
1345,
13,
480,
1758,
12,
20,
3631,
315,
984,
335,
510,
6159,
30,
2631,
384,
6388,
1704,
8863,
203,
3639,
2583,
12,
203,
5411,
290,
1222,
2532,
18,
8443,
951,
12,
82,
1222,
548,
13,
422,
1234,
18,
15330,
16,
203,
5411,
315,
984,
335,
510,
6159,
30,
5098,
326,
3410,
2026,
598,
9446,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
261,
334,
6388,
18,
334,
911,
13649,
18,
1289,
12,
334,
6388,
18,
739,
9384,
3719,
411,
1203,
18,
5508,
16,
203,
5411,
315,
984,
335,
510,
6159,
30,
3488,
813,
486,
7708,
6,
203,
3639,
11272,
203,
3639,
1089,
17631,
14727,
12,
334,
6388,
18,
266,
2913,
1345,
1769,
203,
203,
3639,
534,
359,
1060,
2864,
2502,
2845,
273,
16000,
63,
2867,
12,
334,
6388,
18,
266,
2913,
1345,
13,
15533,
203,
3639,
2583,
12,
2867,
12,
6011,
18,
266,
2913,
1345,
13,
480,
1758,
12,
20,
3631,
315,
984,
335,
510,
6159,
30,
8828,
22296,
8863,
203,
203,
3639,
290,
1222,
2532,
18,
70,
321,
12,
82,
1222,
548,
1769,
203,
203,
3639,
2254,
5034,
5024,
6275,
273,
5024,
6275,
12,
334,
6388,
18,
8949,
16,
384,
6388,
18,
20538,
1769,
203,
203,
3639,
2254,
5034,
24893,
273,
5024,
6275,
18,
16411,
12,
6011,
18,
2
]
|
/**
*Submitted for verification at Etherscan.io on 2022-02-11
*/
// File: node_modules\@openzeppelin\contracts\GSN\Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: node_modules\@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: node_modules\@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: node_modules\@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: @openzeppelin\contracts\math\SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
// File: @openzeppelin\contracts\access\Ownable.sol
// SPDX-License-Identifier: MIT
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\TokenStake.sol
pragma solidity ^0.6.0;
contract TokenStake is Ownable{
using SafeMath for uint256;
ERC20 public token; // Address of token contract
address public tokenOperator; // Address to manage the Stake
uint256 public maxMigrationBlocks; // Block numbers to complete the migration
mapping (address => uint256) public balances; // Useer Token balance in the contract
uint256 public currentStakeMapIndex; // Current Stake Index to avoid math calc in all methods
struct StakeInfo {
bool exist;
uint256 pendingForApprovalAmount;
uint256 approvedAmount;
uint256 rewardComputeIndex;
mapping (uint256 => uint256) claimableAmount;
}
// Staking period timestamp (Debatable on timestamp vs blocknumber - went with timestamp)
struct StakePeriod {
uint256 startPeriod;
uint256 submissionEndPeriod;
uint256 approvalEndPeriod;
uint256 requestWithdrawStartPeriod;
uint256 endPeriod;
uint256 minStake;
bool openForExternal;
uint256 windowRewardAmount;
}
mapping (uint256 => StakePeriod) public stakeMap;
// List of Stake Holders
address[] stakeHolders;
// All Stake Holders
//mapping(address => mapping(uint256 => StakeInfo)) stakeHolderInfo;
mapping(address => StakeInfo) stakeHolderInfo;
// To store the total stake in a window
uint256 public windowTotalStake;
// Events
event NewOperator(address tokenOperator);
event WithdrawToken(address indexed tokenOperator, uint256 amount);
event OpenForStake(uint256 indexed stakeIndex, address indexed tokenOperator, uint256 startPeriod, uint256 endPeriod, uint256 approvalEndPeriod, uint256 rewardAmount);
event SubmitStake(uint256 indexed stakeIndex, address indexed staker, uint256 stakeAmount);
event RequestForClaim(uint256 indexed stakeIndex, address indexed staker, bool autoRenewal);
event ClaimStake(uint256 indexed stakeIndex, address indexed staker, uint256 totalAmount);
event RejectStake(uint256 indexed stakeIndex, address indexed staker, address indexed tokenOperator, uint256 returnAmount);
event AddReward(address indexed staker, uint256 indexed stakeIndex, address tokenOperator, uint256 totalStakeAmount, uint256 rewardAmount, uint256 windowTotalStake);
event WithdrawStake(uint256 indexed stakeIndex, address indexed staker, uint256 stakeAmount);
// Modifiers
modifier onlyOperator() {
require(
msg.sender == tokenOperator,
"Only operator can call this function."
);
_;
}
// Token Operator should be able to do auto renewal
modifier allowSubmission() {
require(
now >= stakeMap[currentStakeMapIndex].startPeriod &&
now <= stakeMap[currentStakeMapIndex].submissionEndPeriod &&
stakeMap[currentStakeMapIndex].openForExternal == true,
"Staking at this point not allowed"
);
_;
}
modifier validStakeLimit(address staker, uint256 stakeAmount) {
uint256 stakerTotalStake;
stakerTotalStake = stakeAmount.add(stakeHolderInfo[staker].pendingForApprovalAmount);
stakerTotalStake = stakerTotalStake.add(stakeHolderInfo[staker].approvedAmount);
// Check for Min Stake
require(
stakeAmount > 0 &&
stakerTotalStake >= stakeMap[currentStakeMapIndex].minStake,
"Need to have min stake"
);
_;
}
// Check for auto renewal flag update
modifier canRequestForClaim(uint256 stakeMapIndex) {
require(
(stakeHolderInfo[msg.sender].approvedAmount > 0 || stakeHolderInfo[msg.sender].claimableAmount[stakeMapIndex] > 0) &&
now >= stakeMap[stakeMapIndex].requestWithdrawStartPeriod &&
now <= stakeMap[stakeMapIndex].endPeriod,
"Update to auto renewal at this point not allowed"
);
_;
}
// Check for claim - after the end period when opted out OR after grace period when no more stake windows
modifier allowClaimStake(uint256 stakeMapIndex) {
uint256 graceTime;
graceTime = stakeMap[stakeMapIndex].endPeriod.sub(stakeMap[stakeMapIndex].requestWithdrawStartPeriod);
require(
(now > stakeMap[stakeMapIndex].endPeriod && stakeHolderInfo[msg.sender].claimableAmount[stakeMapIndex] > 0) ||
(now > stakeMap[stakeMapIndex].endPeriod.add(graceTime) && stakeHolderInfo[msg.sender].approvedAmount > 0), "Invalid claim request"
);
_;
}
constructor(address _token, uint256 _maxMigrationBlocks)
public
{
token = ERC20(_token);
tokenOperator = msg.sender;
currentStakeMapIndex = 0;
windowTotalStake = 0;
maxMigrationBlocks = _maxMigrationBlocks.add(block.number);
}
function updateOperator(address newOperator) public onlyOwner {
require(newOperator != address(0), "Invalid operator address");
tokenOperator = newOperator;
emit NewOperator(newOperator);
}
function withdrawToken(uint256 value) public onlyOperator
{
// Check if contract is having required balance
require(token.balanceOf(address(this)) >= value, "Not enough balance in the contract");
require(token.transfer(msg.sender, value), "Unable to transfer token to the operator account");
emit WithdrawToken(tokenOperator, value);
}
function openForStake(uint256 _startPeriod, uint256 _submissionEndPeriod, uint256 _approvalEndPeriod, uint256 _requestWithdrawStartPeriod, uint256 _endPeriod, uint256 _windowRewardAmount, uint256 _minStake, bool _openForExternal) public onlyOperator {
// Check Input Parameters
require(_startPeriod >= now && _startPeriod < _submissionEndPeriod && _submissionEndPeriod < _approvalEndPeriod && _approvalEndPeriod < _requestWithdrawStartPeriod && _requestWithdrawStartPeriod < _endPeriod, "Invalid stake period");
require(_windowRewardAmount > 0 && _minStake > 0, "Invalid inputs" );
// Check Stake in Progress
require(currentStakeMapIndex == 0 || (now > stakeMap[currentStakeMapIndex].approvalEndPeriod && _startPeriod >= stakeMap[currentStakeMapIndex].requestWithdrawStartPeriod), "Cannot have more than one stake request at a time");
// Move the staking period to next one
currentStakeMapIndex = currentStakeMapIndex + 1;
StakePeriod memory stakePeriod;
// Set Staking attributes
stakePeriod.startPeriod = _startPeriod;
stakePeriod.submissionEndPeriod = _submissionEndPeriod;
stakePeriod.approvalEndPeriod = _approvalEndPeriod;
stakePeriod.requestWithdrawStartPeriod = _requestWithdrawStartPeriod;
stakePeriod.endPeriod = _endPeriod;
stakePeriod.windowRewardAmount = _windowRewardAmount;
stakePeriod.minStake = _minStake;
stakePeriod.openForExternal = _openForExternal;
stakeMap[currentStakeMapIndex] = stakePeriod;
// Add the current window reward to the window total stake
windowTotalStake = windowTotalStake.add(_windowRewardAmount);
emit OpenForStake(currentStakeMapIndex, msg.sender, _startPeriod, _endPeriod, _approvalEndPeriod, _windowRewardAmount);
}
// To add the Stake Holder
function _createStake(address staker, uint256 stakeAmount) internal returns(bool) {
StakeInfo storage stakeInfo = stakeHolderInfo[staker];
// Check if the user already staked in the past
if(stakeInfo.exist) {
stakeInfo.pendingForApprovalAmount = stakeInfo.pendingForApprovalAmount.add(stakeAmount);
} else {
StakeInfo memory req;
// Create a new stake request
req.exist = true;
req.pendingForApprovalAmount = stakeAmount;
req.approvedAmount = 0;
req.rewardComputeIndex = 0;
// Add to the Stake Holders List
stakeHolderInfo[staker] = req;
// Add to the Stake Holders List
stakeHolders.push(staker);
}
return true;
}
// To submit a new stake for the current window
function submitStake(uint256 stakeAmount) public allowSubmission validStakeLimit(msg.sender, stakeAmount) {
// Transfer the Tokens to Contract
require(token.transferFrom(msg.sender, address(this), stakeAmount), "Unable to transfer token to the contract");
_createStake(msg.sender, stakeAmount);
// Update the User balance
balances[msg.sender] = balances[msg.sender].add(stakeAmount);
// Update current stake period total stake - For Auto Approvals
windowTotalStake = windowTotalStake.add(stakeAmount);
emit SubmitStake(currentStakeMapIndex, msg.sender, stakeAmount);
}
// To withdraw stake during submission phase
function withdrawStake(uint256 stakeMapIndex, uint256 stakeAmount) public {
require(
(now >= stakeMap[stakeMapIndex].startPeriod && now <= stakeMap[stakeMapIndex].submissionEndPeriod),
"Stake withdraw at this point is not allowed"
);
StakeInfo storage stakeInfo = stakeHolderInfo[msg.sender];
// Validate the input Stake Amount
require(stakeAmount > 0 &&
stakeInfo.pendingForApprovalAmount >= stakeAmount,
"Cannot withdraw beyond stake amount");
// Allow withdaw not less than minStake or Full Amount
require(
stakeInfo.pendingForApprovalAmount.sub(stakeAmount) >= stakeMap[stakeMapIndex].minStake ||
stakeInfo.pendingForApprovalAmount == stakeAmount,
"Can withdraw full amount or partial amount maintaining min stake"
);
// Update the staker balance in the staking window
stakeInfo.pendingForApprovalAmount = stakeInfo.pendingForApprovalAmount.sub(stakeAmount);
// Update the User balance
balances[msg.sender] = balances[msg.sender].sub(stakeAmount);
// Update current stake period total stake - For Auto Approvals
windowTotalStake = windowTotalStake.sub(stakeAmount);
// Return to User Wallet
require(token.transfer(msg.sender, stakeAmount), "Unable to transfer token to the account");
emit WithdrawStake(stakeMapIndex, msg.sender, stakeAmount);
}
// Reject the stake in the Current Window
function rejectStake(uint256 stakeMapIndex, address staker) public onlyOperator {
// Allow for rejection after approval period as well
require(now > stakeMap[stakeMapIndex].submissionEndPeriod && currentStakeMapIndex == stakeMapIndex, "Rejection at this point is not allowed");
StakeInfo storage stakeInfo = stakeHolderInfo[staker];
// In case of if there are auto renewals reject should not be allowed
require(stakeInfo.pendingForApprovalAmount > 0, "No staking request found");
uint256 returnAmount;
returnAmount = stakeInfo.pendingForApprovalAmount;
// transfer back the stake to user account
require(token.transfer(staker, stakeInfo.pendingForApprovalAmount), "Unable to transfer token back to the account");
// Update the User Balance
balances[staker] = balances[staker].sub(stakeInfo.pendingForApprovalAmount);
// Update current stake period total stake - For Auto Approvals
windowTotalStake = windowTotalStake.sub(stakeInfo.pendingForApprovalAmount);
// Update the Pending Amount
stakeInfo.pendingForApprovalAmount = 0;
emit RejectStake(stakeMapIndex, staker, msg.sender, returnAmount);
}
// To update the Auto Renewal - OptIn or OptOut for next stake window
function requestForClaim(uint256 stakeMapIndex, bool autoRenewal) public canRequestForClaim(stakeMapIndex) {
StakeInfo storage stakeInfo = stakeHolderInfo[msg.sender];
// Check for the claim amount
require((autoRenewal == true && stakeInfo.claimableAmount[stakeMapIndex] > 0) || (autoRenewal == false && stakeInfo.approvedAmount > 0), "Invalid auto renew request");
if(autoRenewal) {
// Update current stake period total stake - For Auto Approvals
windowTotalStake = windowTotalStake.add(stakeInfo.claimableAmount[stakeMapIndex]);
stakeInfo.approvedAmount = stakeInfo.claimableAmount[stakeMapIndex];
stakeInfo.claimableAmount[stakeMapIndex] = 0;
} else {
// Update current stake period total stake - For Auto Approvals
windowTotalStake = windowTotalStake.sub(stakeInfo.approvedAmount);
stakeInfo.claimableAmount[stakeMapIndex] = stakeInfo.approvedAmount;
stakeInfo.approvedAmount = 0;
}
emit RequestForClaim(stakeMapIndex, msg.sender, autoRenewal);
}
function _calculateRewardAmount(uint256 stakeMapIndex, uint256 stakeAmount) internal view returns(uint256) {
uint256 calcRewardAmount;
calcRewardAmount = stakeAmount.mul(stakeMap[stakeMapIndex].windowRewardAmount).div(windowTotalStake.sub(stakeMap[stakeMapIndex].windowRewardAmount));
return calcRewardAmount;
}
// Update reward for staker in the respective stake window
function computeAndAddReward(uint256 stakeMapIndex, address staker)
public
onlyOperator
returns(bool)
{
// Check for the Incubation Period
require(
now > stakeMap[stakeMapIndex].approvalEndPeriod &&
now < stakeMap[stakeMapIndex].requestWithdrawStartPeriod,
"Reward cannot be added now"
);
StakeInfo storage stakeInfo = stakeHolderInfo[staker];
// Check if reward already computed
require((stakeInfo.approvedAmount > 0 || stakeInfo.pendingForApprovalAmount > 0 ) && stakeInfo.rewardComputeIndex != stakeMapIndex, "Invalid reward request");
// Calculate the totalAmount
uint256 totalAmount;
uint256 rewardAmount;
// Calculate the reward amount for the current window - Need to consider pendingForApprovalAmount for Auto Approvals
totalAmount = stakeInfo.approvedAmount.add(stakeInfo.pendingForApprovalAmount);
rewardAmount = _calculateRewardAmount(stakeMapIndex, totalAmount);
totalAmount = totalAmount.add(rewardAmount);
// Add the reward amount and update pendingForApprovalAmount
stakeInfo.approvedAmount = totalAmount;
stakeInfo.pendingForApprovalAmount = 0;
// Update the reward compute index to avoid mulitple addition
stakeInfo.rewardComputeIndex = stakeMapIndex;
// Update the User Balance
balances[staker] = balances[staker].add(rewardAmount);
emit AddReward(staker, stakeMapIndex, tokenOperator, totalAmount, rewardAmount, windowTotalStake);
return true;
}
function updateRewards(uint256 stakeMapIndex, address[] calldata staker)
external
onlyOperator
{
for(uint256 indx = 0; indx < staker.length; indx++) {
require(computeAndAddReward(stakeMapIndex, staker[indx]));
}
}
// To claim from the stake window
function claimStake(uint256 stakeMapIndex) public allowClaimStake(stakeMapIndex) {
StakeInfo storage stakeInfo = stakeHolderInfo[msg.sender];
uint256 stakeAmount;
// General claim
if(stakeInfo.claimableAmount[stakeMapIndex] > 0) {
stakeAmount = stakeInfo.claimableAmount[stakeMapIndex];
stakeInfo.claimableAmount[stakeMapIndex] = 0;
} else {
// No more stake windows & beyond grace period
stakeAmount = stakeInfo.approvedAmount;
stakeInfo.approvedAmount = 0;
// Update current stake period total stake
windowTotalStake = windowTotalStake.sub(stakeAmount);
}
// Check for balance in the contract
require(token.balanceOf(address(this)) >= stakeAmount, "Not enough balance in the contract");
// Update the User Balance
balances[msg.sender] = balances[msg.sender].sub(stakeAmount);
// Call the transfer function
require(token.transfer(msg.sender, stakeAmount), "Unable to transfer token back to the account");
emit ClaimStake(stakeMapIndex, msg.sender, stakeAmount);
}
// Migration - Load existing Stake Windows & Stakers
function migrateStakeWindow(uint256 _startPeriod, uint256 _submissionEndPeriod, uint256 _approvalEndPeriod, uint256 _requestWithdrawStartPeriod, uint256 _endPeriod, uint256 _windowRewardAmount, uint256 _minStake, bool _openForExternal) public onlyOperator {
// Add check for Block Number to restrict migration after certain block number
require(block.number < maxMigrationBlocks, "Exceeds migration phase");
// Check Input Parameters for past stake windows
require(now > _startPeriod && _startPeriod < _submissionEndPeriod && _submissionEndPeriod < _approvalEndPeriod && _approvalEndPeriod < _requestWithdrawStartPeriod && _requestWithdrawStartPeriod < _endPeriod, "Invalid stake period");
require(_windowRewardAmount > 0 && _minStake > 0, "Invalid inputs" );
// Move the staking period to next one
currentStakeMapIndex = currentStakeMapIndex + 1;
StakePeriod memory stakePeriod;
// Set Staking attributes
stakePeriod.startPeriod = _startPeriod;
stakePeriod.submissionEndPeriod = _submissionEndPeriod;
stakePeriod.approvalEndPeriod = _approvalEndPeriod;
stakePeriod.requestWithdrawStartPeriod = _requestWithdrawStartPeriod;
stakePeriod.endPeriod = _endPeriod;
stakePeriod.windowRewardAmount = _windowRewardAmount;
stakePeriod.minStake = _minStake;
stakePeriod.openForExternal = _openForExternal;
stakeMap[currentStakeMapIndex] = stakePeriod;
}
// Migration - Load existing stakes along with computed reward
function migrateStakes(uint256 stakeMapIndex, address[] calldata staker, uint256[] calldata stakeAmount) external onlyOperator {
// Add check for Block Number to restrict migration after certain block number
require(block.number < maxMigrationBlocks, "Exceeds migration phase");
// Check Input Parameters
require(staker.length == stakeAmount.length, "Invalid Input Arrays");
// Stakers should be for current window
require(currentStakeMapIndex == stakeMapIndex, "Invalid Stake Window Index");
for(uint256 indx = 0; indx < staker.length; indx++) {
StakeInfo memory req;
// Create a stake request with approvedAmount
req.exist = true;
req.pendingForApprovalAmount = 0;
req.approvedAmount = stakeAmount[indx];
req.rewardComputeIndex = stakeMapIndex;
// Add to the Stake Holders List
stakeHolderInfo[staker[indx]] = req;
// Add to the Stake Holders List
stakeHolders.push(staker[indx]);
// Update the User balance
balances[staker[indx]] = stakeAmount[indx];
// Update current stake period total stake - Along with Reward
windowTotalStake = windowTotalStake.add(stakeAmount[indx]);
}
}
// Getter Functions
function getStakeHolders() public view returns(address[] memory) {
return stakeHolders;
}
function getStakeInfo(uint256 stakeMapIndex, address staker)
public
view
returns (bool found, uint256 approvedAmount, uint256 pendingForApprovalAmount, uint256 rewardComputeIndex, uint256 claimableAmount)
{
StakeInfo storage stakeInfo = stakeHolderInfo[staker];
found = false;
if(stakeInfo.exist) {
found = true;
}
pendingForApprovalAmount = stakeInfo.pendingForApprovalAmount;
approvedAmount = stakeInfo.approvedAmount;
rewardComputeIndex = stakeInfo.rewardComputeIndex;
claimableAmount = stakeInfo.claimableAmount[stakeMapIndex];
}
} | Migration - Load existing Stake Windows & Stakers Add check for Block Number to restrict migration after certain block number Check Input Parameters for past stake windows Move the staking period to next one Set Staking attributes | function migrateStakeWindow(uint256 _startPeriod, uint256 _submissionEndPeriod, uint256 _approvalEndPeriod, uint256 _requestWithdrawStartPeriod, uint256 _endPeriod, uint256 _windowRewardAmount, uint256 _minStake, bool _openForExternal) public onlyOperator {
require(block.number < maxMigrationBlocks, "Exceeds migration phase");
require(now > _startPeriod && _startPeriod < _submissionEndPeriod && _submissionEndPeriod < _approvalEndPeriod && _approvalEndPeriod < _requestWithdrawStartPeriod && _requestWithdrawStartPeriod < _endPeriod, "Invalid stake period");
require(_windowRewardAmount > 0 && _minStake > 0, "Invalid inputs" );
currentStakeMapIndex = currentStakeMapIndex + 1;
StakePeriod memory stakePeriod;
stakePeriod.startPeriod = _startPeriod;
stakePeriod.submissionEndPeriod = _submissionEndPeriod;
stakePeriod.approvalEndPeriod = _approvalEndPeriod;
stakePeriod.requestWithdrawStartPeriod = _requestWithdrawStartPeriod;
stakePeriod.endPeriod = _endPeriod;
stakePeriod.windowRewardAmount = _windowRewardAmount;
stakePeriod.minStake = _minStake;
stakePeriod.openForExternal = _openForExternal;
stakeMap[currentStakeMapIndex] = stakePeriod;
}
| 7,971,061 | [
1,
10224,
300,
4444,
2062,
934,
911,
8202,
473,
934,
581,
414,
1436,
866,
364,
3914,
3588,
358,
13108,
6333,
1839,
8626,
1203,
1300,
2073,
2741,
7012,
364,
8854,
384,
911,
9965,
9933,
326,
384,
6159,
3879,
358,
1024,
1245,
1000,
934,
6159,
1677,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
13187,
510,
911,
3829,
12,
11890,
5034,
389,
1937,
5027,
16,
2254,
5034,
389,
12684,
1638,
5027,
16,
225,
2254,
5034,
389,
12908,
1125,
1638,
5027,
16,
2254,
5034,
389,
2293,
1190,
9446,
1685,
5027,
16,
2254,
5034,
389,
409,
5027,
16,
2254,
5034,
389,
5668,
17631,
1060,
6275,
16,
2254,
5034,
389,
1154,
510,
911,
16,
1426,
389,
3190,
1290,
6841,
13,
1071,
1338,
5592,
288,
203,
203,
3639,
2583,
12,
2629,
18,
2696,
411,
943,
10224,
6450,
16,
315,
424,
5288,
87,
6333,
6855,
8863,
203,
203,
3639,
2583,
12,
3338,
405,
389,
1937,
5027,
597,
389,
1937,
5027,
411,
389,
12684,
1638,
5027,
597,
389,
12684,
1638,
5027,
411,
389,
12908,
1125,
1638,
5027,
597,
389,
12908,
1125,
1638,
5027,
411,
389,
2293,
1190,
9446,
1685,
5027,
597,
389,
2293,
1190,
9446,
1685,
5027,
411,
389,
409,
5027,
16,
315,
1941,
384,
911,
3879,
8863,
203,
3639,
2583,
24899,
5668,
17631,
1060,
6275,
405,
374,
597,
389,
1154,
510,
911,
405,
374,
16,
315,
1941,
4540,
6,
11272,
203,
203,
3639,
783,
510,
911,
863,
1016,
273,
783,
510,
911,
863,
1016,
397,
404,
31,
203,
3639,
934,
911,
5027,
3778,
384,
911,
5027,
31,
203,
203,
3639,
384,
911,
5027,
18,
1937,
5027,
273,
389,
1937,
5027,
31,
203,
3639,
384,
911,
5027,
18,
12684,
1638,
5027,
273,
389,
12684,
1638,
5027,
31,
203,
3639,
384,
911,
5027,
18,
12908,
1125,
1638,
5027,
273,
389,
12908,
1125,
1638,
5027,
31,
203,
3639,
384,
911,
5027,
18,
2293,
1190,
2
]
|
pragma solidity ^0.4.18;
contract owned {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
contract WeiFangQiCoin is owned {
string constant public name="Wei Fang Qi Coin";
uint8 constant public decimals=2;
string constant public symbol="WFQ";
uint256 constant private _initialAmount = 950000;
uint256 constant private MAX_UINT256 = 2**256 - 1;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowed;
uint256 public sellPrice; //=10000000000000000;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Burn(address indexed _from,uint256 _value);
event FrozenFunds(address indexed target, bool frozen);
event MintToken(address indexed target,uint256 _value);
event Buy(address indexed target,uint256 _value);
event WithDraw(address _value);
constructor(
/* uint256 _initialAmount,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol */)
public payable {
uint256 mint_total=_initialAmount * 10 ** uint256(decimals);
balanceOf[msg.sender] = mint_total;
totalSupply = mint_total;
/*
name = _tokenName;
decimals = _decimalUnits;
symbol = _tokenSymbol;
*/
}
function() public payable {
buy();
}
function buy() payable public returns (bool success) {
//require(!frozenAccount[msg.sender]);
uint256 amount = msg.value / buyPrice;
_transfer(owner, msg.sender, amount);
emit Buy(msg.sender,amount);
//token(owner).transfer(msg.sender,msg.value);
return true;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
if (_from == _to)
return;
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender,_to,_value);
return true;
}
/*
function adminTransfer(address _from,address _to, uint256 _value) onlyOwner public returns (bool success) {
_transfer(_from,_to,_value);
return true;
}*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balanceOf[_from] >= _value && allowance >= _value);
_transfer(_from,_to,_value);
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function burn(uint256 _value) public {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
//balanceOf[msg.sender] -= _value * 10 ** uint256(decimals);
//totalSupply -= _value * 10 ** uint256(decimals);
emit Burn(msg.sender, _value);
}
function burnFrom(address _from, uint256 _value) public {
require(balanceOf[_from] >= _value);
require(_value <= allowed[_from][msg.sender]);
balanceOf[_from] -= _value;
allowed[_from][msg.sender] -= _value;
totalSupply -= _value;
/*
balanceOf[_from] -= _value * 10 ** uint256(decimals);
allowed[_from][msg.sender] -= _value * 10 ** uint256(decimals);
totalSupply -= _value * 10 ** uint256(decimals);
*/
emit Burn(_from, _value);
}
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
//balanceOf[target] += mintedAmount * 10 ** uint256(decimals);
//totalSupply += mintedAmount * 10 ** uint256(decimals);
//emit Transfer(0, this, mintedAmount);
//emit Transfer(this, target, mintedAmount);
emit MintToken(target,mintedAmount);
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
function sell(uint256 _amount) public returns (bool success){
require(!frozenAccount[msg.sender]);
//uint256 amount = _amount * 10 ** uint256(decimals);
require(balanceOf[msg.sender] >= _amount);
require(address(this).balance >= _amount * sellPrice);
_transfer(msg.sender, owner, _amount);
if (!msg.sender.send(_amount * sellPrice)) {
return false;
}
return true;
}
function withdraw(address target) onlyOwner public {
//require(withdrawPassword == 888888);
target.transfer(address(this).balance);
emit WithDraw(target);
/*
if (!msg.sender.send(amount)) {
return false;
}
*/
}
/*
function withDrawInWei(uint256 amount) onlyOwner public returns (bool) {
if (!msg.sender.send(amount)) {
return false;
}
return true;
}
*/
function killSelf(uint256 target) onlyOwner public returns (bool success){
if (target == 31415926){
selfdestruct(owner);
return true;
}
return false;
}
} | balanceOf[target] += mintedAmount * 10 ** uint256(decimals);totalSupply += mintedAmount * 10 ** uint256(decimals);emit Transfer(0, this, mintedAmount);emit Transfer(this, target, mintedAmount); | function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
emit MintToken(target,mintedAmount);
}
| 14,124,971 | [
1,
12296,
951,
63,
3299,
65,
1011,
312,
474,
329,
6275,
225,
1728,
225,
2254,
5034,
12,
31734,
1769,
4963,
3088,
1283,
1011,
312,
474,
329,
6275,
225,
1728,
225,
2254,
5034,
12,
31734,
1769,
18356,
12279,
12,
20,
16,
333,
16,
312,
474,
329,
6275,
1769,
18356,
12279,
12,
2211,
16,
1018,
16,
312,
474,
329,
6275,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
312,
474,
1345,
12,
2867,
1018,
16,
2254,
5034,
312,
474,
329,
6275,
13,
1338,
5541,
1071,
288,
203,
3639,
11013,
951,
63,
3299,
65,
1011,
312,
474,
329,
6275,
31,
203,
3639,
2078,
3088,
1283,
1011,
312,
474,
329,
6275,
31,
203,
3639,
3626,
490,
474,
1345,
12,
3299,
16,
81,
474,
329,
6275,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.5.17;
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO";
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
require(c / _a == _b, ERROR_MUL_OVERFLOW);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0
uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a, ERROR_SUB_UNDERFLOW);
uint256 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a, ERROR_ADD_OVERFLOW);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, ERROR_DIV_ZERO);
return a % b;
}
}
/*
* SPDX-License-Identifier: MIT
*/
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() external view returns (uint256);
function balanceOf(address _who) external view returns (uint256);
function allowance(address _owner, address _spender) external view returns (uint256);
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);
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/SafeERC20.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
library SafeERC20 {
/**
* @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false).
* Note that this makes an external call to the provided token and expects it to be already
* verified as a contract.
*/
function safeTransfer(IERC20 _token, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferCallData = abi.encodeWithSelector(
_token.transfer.selector,
_to,
_amount
);
return invokeAndCheckSuccess(address(_token), transferCallData);
}
/**
* @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false).
* Note that this makes an external call to the provided token and expects it to be already
* verified as a contract.
*/
function safeTransferFrom(IERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferFromCallData = abi.encodeWithSelector(
_token.transferFrom.selector,
_from,
_to,
_amount
);
return invokeAndCheckSuccess(address(_token), transferFromCallData);
}
/**
* @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false).
* Note that this makes an external call to the provided token and expects it to be already
* verified as a contract.
*/
function safeApprove(IERC20 _token, address _spender, uint256 _amount) internal returns (bool) {
bytes memory approveCallData = abi.encodeWithSelector(
_token.approve.selector,
_spender,
_amount
);
return invokeAndCheckSuccess(address(_token), approveCallData);
}
function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) {
bool ret;
assembly {
let ptr := mload(0x40) // free memory pointer
let success := call(
gas, // forward all gas
_addr, // address
0, // no value
add(_calldata, 0x20), // calldata start
mload(_calldata), // calldata length
ptr, // write output over free memory
0x20 // uint256 return
)
if gt(success, 0) {
// Check number of bytes returned from last function call
switch returndatasize
// No bytes returned: assume success
case 0 {
ret := 1
}
// 32 bytes returned: check if non-zero
case 0x20 {
// Only return success if returned data was true
// Already have output in ptr
ret := eq(mload(ptr), 1)
}
// Not sure what was returned: don't mark as success
default { }
}
}
return ret;
}
}
library PctHelpers {
using SafeMath for uint256;
uint256 internal constant PCT_BASE = 10000; // ‱ (1 / 10,000)
function isValid(uint16 _pct) internal pure returns (bool) {
return _pct <= PCT_BASE;
}
function pct(uint256 self, uint16 _pct) internal pure returns (uint256) {
return self.mul(uint256(_pct)) / PCT_BASE;
}
function pct256(uint256 self, uint256 _pct) internal pure returns (uint256) {
return self.mul(_pct) / PCT_BASE;
}
function pctIncrease(uint256 self, uint16 _pct) internal pure returns (uint256) {
// No need for SafeMath: for addition note that `PCT_BASE` is lower than (2^256 - 2^16)
return self.mul(PCT_BASE + uint256(_pct)) / PCT_BASE;
}
}
/**
* @title Checkpointing - Library to handle a historic set of numeric values
*/
library Checkpointing {
uint256 private constant MAX_UINT192 = uint256(uint192(-1));
string private constant ERROR_VALUE_TOO_BIG = "CHECKPOINT_VALUE_TOO_BIG";
string private constant ERROR_CANNOT_ADD_PAST_VALUE = "CHECKPOINT_CANNOT_ADD_PAST_VALUE";
/**
* @dev To specify a value at a given point in time, we need to store two values:
* - `time`: unit-time value to denote the first time when a value was registered
* - `value`: a positive numeric value to registered at a given point in time
*
* Note that `time` does not need to refer necessarily to a timestamp value, any time unit could be used
* for it like block numbers, terms, etc.
*/
struct Checkpoint {
uint64 time;
uint192 value;
}
/**
* @dev A history simply denotes a list of checkpoints
*/
struct History {
Checkpoint[] history;
}
/**
* @dev Add a new value to a history for a given point in time. This function does not allow to add values previous
* to the latest registered value, if the value willing to add corresponds to the latest registered value, it
* will be updated.
* @param self Checkpoints history to be altered
* @param _time Point in time to register the given value
* @param _value Numeric value to be registered at the given point in time
*/
function add(History storage self, uint64 _time, uint256 _value) internal {
require(_value <= MAX_UINT192, ERROR_VALUE_TOO_BIG);
_add192(self, _time, uint192(_value));
}
/**
* @dev Fetch the latest registered value of history, it will return zero if there was no value registered
* @param self Checkpoints history to be queried
*/
function getLast(History storage self) internal view returns (uint256) {
uint256 length = self.history.length;
if (length > 0) {
return uint256(self.history[length - 1].value);
}
return 0;
}
/**
* @dev Fetch the most recent registered past value of a history based on a given point in time that is not known
* how recent it is beforehand. It will return zero if there is no registered value or if given time is
* previous to the first registered value.
* It uses a binary search.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function get(History storage self, uint64 _time) internal view returns (uint256) {
return _binarySearch(self, _time);
}
/**
* @dev Fetch the most recent registered past value of a history based on a given point in time. It will return zero
* if there is no registered value or if given time is previous to the first registered value.
* It uses a linear search starting from the end.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function getRecent(History storage self, uint64 _time) internal view returns (uint256) {
return _backwardsLinearSearch(self, _time);
}
/**
* @dev Private function to add a new value to a history for a given point in time. This function does not allow to
* add values previous to the latest registered value, if the value willing to add corresponds to the latest
* registered value, it will be updated.
* @param self Checkpoints history to be altered
* @param _time Point in time to register the given value
* @param _value Numeric value to be registered at the given point in time
*/
function _add192(History storage self, uint64 _time, uint192 _value) private {
uint256 length = self.history.length;
if (length == 0 || self.history[self.history.length - 1].time < _time) {
// If there was no value registered or the given point in time is after the latest registered value,
// we can insert it to the history directly.
self.history.push(Checkpoint(_time, _value));
} else {
// If the point in time given for the new value is not after the latest registered value, we must ensure
// we are only trying to update the latest value, otherwise we would be changing past data.
Checkpoint storage currentCheckpoint = self.history[length - 1];
require(_time == currentCheckpoint.time, ERROR_CANNOT_ADD_PAST_VALUE);
currentCheckpoint.value = _value;
}
}
/**
* @dev Private function to execute a backwards linear search to find the most recent registered past value of a
* history based on a given point in time. It will return zero if there is no registered value or if given time
* is previous to the first registered value. Note that this function will be more suitable when we already know
* that the time used to index the search is recent in the given history.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function _backwardsLinearSearch(History storage self, uint64 _time) private view returns (uint256) {
// If there was no value registered for the given history return simply zero
uint256 length = self.history.length;
if (length == 0) {
return 0;
}
uint256 index = length - 1;
Checkpoint storage checkpoint = self.history[index];
while (index > 0 && checkpoint.time > _time) {
index--;
checkpoint = self.history[index];
}
return checkpoint.time > _time ? 0 : uint256(checkpoint.value);
}
/**
* @dev Private function execute a binary search to find the most recent registered past value of a history based on
* a given point in time. It will return zero if there is no registered value or if given time is previous to
* the first registered value. Note that this function will be more suitable when don't know how recent the
* time used to index may be.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function _binarySearch(History storage self, uint64 _time) private view returns (uint256) {
// If there was no value registered for the given history return simply zero
uint256 length = self.history.length;
if (length == 0) {
return 0;
}
// If the requested time is equal to or after the time of the latest registered value, return latest value
uint256 lastIndex = length - 1;
if (_time >= self.history[lastIndex].time) {
return uint256(self.history[lastIndex].value);
}
// If the requested time is previous to the first registered value, return zero to denote missing checkpoint
if (_time < self.history[0].time) {
return 0;
}
// Execute a binary search between the checkpointed times of the history
uint256 low = 0;
uint256 high = lastIndex;
while (high > low) {
// No need for SafeMath: for this to overflow array size should be ~2^255
uint256 mid = (high + low + 1) / 2;
Checkpoint storage checkpoint = self.history[mid];
uint64 midTime = checkpoint.time;
if (_time > midTime) {
low = mid;
} else if (_time < midTime) {
// No need for SafeMath: high > low >= 0 => high >= 1 => mid >= 1
high = mid - 1;
} else {
return uint256(checkpoint.value);
}
}
return uint256(self.history[low].value);
}
}
/**
* @title HexSumTree - Library to operate checkpointed 16-ary (hex) sum trees.
* @dev A sum tree is a particular case of a tree where the value of a node is equal to the sum of the values of its
* children. This library provides a set of functions to operate 16-ary sum trees, i.e. trees where every non-leaf
* node has 16 children and its value is equivalent to the sum of the values of all of them. Additionally, a
* checkpointed tree means that each time a value on a node is updated, its previous value will be saved to allow
* accessing historic information.
*
* Example of a checkpointed binary sum tree:
*
* CURRENT PREVIOUS
*
* Level 2 100 ---------------------------------------- 70
* ______|_______ ______|_______
* / \ / \
* Level 1 34 66 ------------------------- 23 47
* _____|_____ _____|_____ _____|_____ _____|_____
* / \ / \ / \ / \
* Level 0 22 12 53 13 ----------- 22 1 17 30
*
*/
library HexSumTree {
using SafeMath for uint256;
using Checkpointing for Checkpointing.History;
string private constant ERROR_UPDATE_OVERFLOW = "SUM_TREE_UPDATE_OVERFLOW";
string private constant ERROR_KEY_DOES_NOT_EXIST = "SUM_TREE_KEY_DOES_NOT_EXIST";
string private constant ERROR_SEARCH_OUT_OF_BOUNDS = "SUM_TREE_SEARCH_OUT_OF_BOUNDS";
string private constant ERROR_MISSING_SEARCH_VALUES = "SUM_TREE_MISSING_SEARCH_VALUES";
// Constants used to perform tree computations
// To change any the following constants, the following relationship must be kept: 2^BITS_IN_NIBBLE = CHILDREN
// The max depth of the tree will be given by: BITS_IN_NIBBLE * MAX_DEPTH = 256 (so in this case it's 64)
uint256 private constant CHILDREN = 16;
uint256 private constant BITS_IN_NIBBLE = 4;
// All items are leaves, inserted at height or level zero. The root height will be increasing as new levels are inserted in the tree.
uint256 private constant ITEMS_LEVEL = 0;
// Tree nodes are identified with a 32-bytes length key. Leaves are identified with consecutive incremental keys
// starting with 0x0000000000000000000000000000000000000000000000000000000000000000, while non-leaf nodes' keys
// are computed based on their level and their children keys.
uint256 private constant BASE_KEY = 0;
// Timestamp used to checkpoint the first value of the tree height during initialization
uint64 private constant INITIALIZATION_INITIAL_TIME = uint64(0);
/**
* @dev The tree is stored using the following structure:
* - nodes: A mapping indexed by a pair (level, key) with a history of the values for each node (level -> key -> value).
* - height: A history of the heights of the tree. Minimum height is 1, a root with 16 children.
* - nextKey: The next key to be used to identify the next new value that will be inserted into the tree.
*/
struct Tree {
uint256 nextKey;
Checkpointing.History height;
mapping (uint256 => mapping (uint256 => Checkpointing.History)) nodes;
}
/**
* @dev Search params to traverse the tree caching previous results:
* - time: Point in time to query the values being searched, this value shouldn't change during a search
* - level: Level being analyzed for the search, it starts at the level under the root and decrements till the leaves
* - parentKey: Key of the parent of the nodes being analyzed at the given level for the search
* - foundValues: Number of values in the list being searched that were already found, it will go from 0 until the size of the list
* - visitedTotal: Total sum of values that were already visited during the search, it will go from 0 until the tree total
*/
struct SearchParams {
uint64 time;
uint256 level;
uint256 parentKey;
uint256 foundValues;
uint256 visitedTotal;
}
/**
* @dev Initialize tree setting the next key and first height checkpoint
*/
function init(Tree storage self) internal {
self.height.add(INITIALIZATION_INITIAL_TIME, ITEMS_LEVEL + 1);
self.nextKey = BASE_KEY;
}
/**
* @dev Insert a new item to the tree at given point in time
* @param _time Point in time to register the given value
* @param _value New numeric value to be added to the tree
* @return Unique key identifying the new value inserted
*/
function insert(Tree storage self, uint64 _time, uint256 _value) internal returns (uint256) {
// As the values are always stored in the leaves of the tree (level 0), the key to index each of them will be
// always incrementing, starting from zero. Add a new level if necessary.
uint256 key = self.nextKey++;
_addLevelIfNecessary(self, key, _time);
// If the new value is not zero, first set the value of the new leaf node, then add a new level at the top of
// the tree if necessary, and finally update sums cached in all the non-leaf nodes.
if (_value > 0) {
_add(self, ITEMS_LEVEL, key, _time, _value);
_updateSums(self, key, _time, _value, true);
}
return key;
}
/**
* @dev Set the value of a leaf node indexed by its key at given point in time
* @param _time Point in time to set the given value
* @param _key Key of the leaf node to be set in the tree
* @param _value New numeric value to be set for the given key
*/
function set(Tree storage self, uint256 _key, uint64 _time, uint256 _value) internal {
require(_key < self.nextKey, ERROR_KEY_DOES_NOT_EXIST);
// Set the new value for the requested leaf node
uint256 lastValue = getItem(self, _key);
_add(self, ITEMS_LEVEL, _key, _time, _value);
// Update sums cached in the non-leaf nodes. Note that overflows are being checked at the end of the whole update.
if (_value > lastValue) {
_updateSums(self, _key, _time, _value - lastValue, true);
} else if (_value < lastValue) {
_updateSums(self, _key, _time, lastValue - _value, false);
}
}
/**
* @dev Update the value of a non-leaf node indexed by its key at given point in time based on a delta
* @param _key Key of the leaf node to be updated in the tree
* @param _time Point in time to update the given value
* @param _delta Numeric delta to update the value of the given key
* @param _positive Boolean to tell whether the given delta should be added to or subtracted from the current value
*/
function update(Tree storage self, uint256 _key, uint64 _time, uint256 _delta, bool _positive) internal {
require(_key < self.nextKey, ERROR_KEY_DOES_NOT_EXIST);
// Update the value of the requested leaf node based on the given delta
uint256 lastValue = getItem(self, _key);
uint256 newValue = _positive ? lastValue.add(_delta) : lastValue.sub(_delta);
_add(self, ITEMS_LEVEL, _key, _time, newValue);
// Update sums cached in the non-leaf nodes. Note that overflows is being checked at the end of the whole update.
_updateSums(self, _key, _time, _delta, _positive);
}
/**
* @dev Search a list of values in the tree at a given point in time. It will return a list with the nearest
* high value in case a value cannot be found. This function assumes the given list of given values to be
* searched is in ascending order. In case of searching a value out of bounds, it will return zeroed results.
* @param _values Ordered list of values to be searched in the tree
* @param _time Point in time to query the values being searched
* @return keys List of keys found for each requested value in the same order
* @return values List of node values found for each requested value in the same order
*/
function search(Tree storage self, uint256[] memory _values, uint64 _time) internal view
returns (uint256[] memory keys, uint256[] memory values)
{
require(_values.length > 0, ERROR_MISSING_SEARCH_VALUES);
// Throw out-of-bounds error if there are no items in the tree or the highest value being searched is greater than the total
uint256 total = getRecentTotalAt(self, _time);
// No need for SafeMath: positive length of array already checked
require(total > 0 && total > _values[_values.length - 1], ERROR_SEARCH_OUT_OF_BOUNDS);
// Build search params for the first iteration
uint256 rootLevel = getRecentHeightAt(self, _time);
SearchParams memory searchParams = SearchParams(_time, rootLevel.sub(1), BASE_KEY, 0, 0);
// These arrays will be used to fill in the results. We are passing them as parameters to avoid extra copies
uint256 length = _values.length;
keys = new uint256[](length);
values = new uint256[](length);
_search(self, _values, searchParams, keys, values);
}
/**
* @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree
*/
function getTotal(Tree storage self) internal view returns (uint256) {
uint256 rootLevel = getHeight(self);
return getNode(self, rootLevel, BASE_KEY);
}
/**
* @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree, at a given point in time
* It uses a binary search for the root node, a linear one for the height.
* @param _time Point in time to query the sum of all the items (leaves) stored in the tree
*/
function getTotalAt(Tree storage self, uint64 _time) internal view returns (uint256) {
uint256 rootLevel = getRecentHeightAt(self, _time);
return getNodeAt(self, rootLevel, BASE_KEY, _time);
}
/**
* @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree, at a given point in time
* It uses a linear search starting from the end.
* @param _time Point in time to query the sum of all the items (leaves) stored in the tree
*/
function getRecentTotalAt(Tree storage self, uint64 _time) internal view returns (uint256) {
uint256 rootLevel = getRecentHeightAt(self, _time);
return getRecentNodeAt(self, rootLevel, BASE_KEY, _time);
}
/**
* @dev Tell the value of a certain leaf indexed by a given key
* @param _key Key of the leaf node querying the value of
*/
function getItem(Tree storage self, uint256 _key) internal view returns (uint256) {
return getNode(self, ITEMS_LEVEL, _key);
}
/**
* @dev Tell the value of a certain leaf indexed by a given key at a given point in time
* It uses a binary search.
* @param _key Key of the leaf node querying the value of
* @param _time Point in time to query the value of the requested leaf
*/
function getItemAt(Tree storage self, uint256 _key, uint64 _time) internal view returns (uint256) {
return getNodeAt(self, ITEMS_LEVEL, _key, _time);
}
/**
* @dev Tell the value of a certain node indexed by a given (level,key) pair
* @param _level Level of the node querying the value of
* @param _key Key of the node querying the value of
*/
function getNode(Tree storage self, uint256 _level, uint256 _key) internal view returns (uint256) {
return self.nodes[_level][_key].getLast();
}
/**
* @dev Tell the value of a certain node indexed by a given (level,key) pair at a given point in time
* It uses a binary search.
* @param _level Level of the node querying the value of
* @param _key Key of the node querying the value of
* @param _time Point in time to query the value of the requested node
*/
function getNodeAt(Tree storage self, uint256 _level, uint256 _key, uint64 _time) internal view returns (uint256) {
return self.nodes[_level][_key].get(_time);
}
/**
* @dev Tell the value of a certain node indexed by a given (level,key) pair at a given point in time
* It uses a linear search starting from the end.
* @param _level Level of the node querying the value of
* @param _key Key of the node querying the value of
* @param _time Point in time to query the value of the requested node
*/
function getRecentNodeAt(Tree storage self, uint256 _level, uint256 _key, uint64 _time) internal view returns (uint256) {
return self.nodes[_level][_key].getRecent(_time);
}
/**
* @dev Tell the height of the tree
*/
function getHeight(Tree storage self) internal view returns (uint256) {
return self.height.getLast();
}
/**
* @dev Tell the height of the tree at a given point in time
* It uses a linear search starting from the end.
* @param _time Point in time to query the height of the tree
*/
function getRecentHeightAt(Tree storage self, uint64 _time) internal view returns (uint256) {
return self.height.getRecent(_time);
}
/**
* @dev Private function to update the values of all the ancestors of the given leaf node based on the delta updated
* @param _key Key of the leaf node to update the ancestors of
* @param _time Point in time to update the ancestors' values of the given leaf node
* @param _delta Numeric delta to update the ancestors' values of the given leaf node
* @param _positive Boolean to tell whether the given delta should be added to or subtracted from ancestors' values
*/
function _updateSums(Tree storage self, uint256 _key, uint64 _time, uint256 _delta, bool _positive) private {
uint256 mask = uint256(-1);
uint256 ancestorKey = _key;
uint256 currentHeight = getHeight(self);
for (uint256 level = ITEMS_LEVEL + 1; level <= currentHeight; level++) {
// Build a mask to get the key of the ancestor at a certain level. For example:
// Level 0: leaves don't have children
// Level 1: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0 (up to 16 leaves)
// Level 2: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 (up to 32 leaves)
// ...
// Level 63: 0x0000000000000000000000000000000000000000000000000000000000000000 (up to 16^64 leaves - tree max height)
mask = mask << BITS_IN_NIBBLE;
// The key of the ancestor at that level "i" is equivalent to the "(64 - i)-th" most significant nibbles
// of the ancestor's key of the previous level "i - 1". Thus, we can compute the key of an ancestor at a
// certain level applying the mask to the ancestor's key of the previous level. Note that for the first
// iteration, the key of the ancestor of the previous level is simply the key of the leaf being updated.
ancestorKey = ancestorKey & mask;
// Update value
uint256 lastValue = getNode(self, level, ancestorKey);
uint256 newValue = _positive ? lastValue.add(_delta) : lastValue.sub(_delta);
_add(self, level, ancestorKey, _time, newValue);
}
// Check if there was an overflow. Note that we only need to check the value stored in the root since the
// sum only increases going up through the tree.
require(!_positive || getNode(self, currentHeight, ancestorKey) >= _delta, ERROR_UPDATE_OVERFLOW);
}
/**
* @dev Private function to add a new level to the tree based on a new key that will be inserted
* @param _newKey New key willing to be inserted in the tree
* @param _time Point in time when the new key will be inserted
*/
function _addLevelIfNecessary(Tree storage self, uint256 _newKey, uint64 _time) private {
uint256 currentHeight = getHeight(self);
if (_shouldAddLevel(currentHeight, _newKey)) {
// Max height allowed for the tree is 64 since we are using node keys of 32 bytes. However, note that we
// are not checking if said limit has been hit when inserting new leaves to the tree, for the purpose of
// this system having 2^256 items inserted is unrealistic.
uint256 newHeight = currentHeight + 1;
uint256 rootValue = getNode(self, currentHeight, BASE_KEY);
_add(self, newHeight, BASE_KEY, _time, rootValue);
self.height.add(_time, newHeight);
}
}
/**
* @dev Private function to register a new value in the history of a node at a given point in time
* @param _level Level of the node to add a new value at a given point in time to
* @param _key Key of the node to add a new value at a given point in time to
* @param _time Point in time to register a value for the given node
* @param _value Numeric value to be registered for the given node at a given point in time
*/
function _add(Tree storage self, uint256 _level, uint256 _key, uint64 _time, uint256 _value) private {
self.nodes[_level][_key].add(_time, _value);
}
/**
* @dev Recursive pre-order traversal function
* Every time it checks a node, it traverses the input array to find the initial subset of elements that are
* below its accumulated value and passes that sub-array to the next iteration. Actually, the array is always
* the same, to avoid making extra copies, it just passes the number of values already found , to avoid
* checking values that went through a different branch. The same happens with the result lists of keys and
* values, these are the same on every recursion step. The visited total is carried over each iteration to
* avoid having to subtract all elements in the array.
* @param _values Ordered list of values to be searched in the tree
* @param _params Search parameters for the current recursive step
* @param _resultKeys List of keys found for each requested value in the same order
* @param _resultValues List of node values found for each requested value in the same order
*/
function _search(
Tree storage self,
uint256[] memory _values,
SearchParams memory _params,
uint256[] memory _resultKeys,
uint256[] memory _resultValues
)
private
view
{
uint256 levelKeyLessSignificantNibble = _params.level.mul(BITS_IN_NIBBLE);
for (uint256 childNumber = 0; childNumber < CHILDREN; childNumber++) {
// Return if we already found enough values
if (_params.foundValues >= _values.length) {
break;
}
// Build child node key shifting the child number to the position of the less significant nibble of
// the keys for the level being analyzed, and adding it to the key of the parent node. For example,
// for a tree with height 5, if we are checking the children of the second node of the level 3, whose
// key is 0x0000000000000000000000000000000000000000000000000000000000001000, its children keys are:
// Child 0: 0x0000000000000000000000000000000000000000000000000000000000001000
// Child 1: 0x0000000000000000000000000000000000000000000000000000000000001100
// Child 2: 0x0000000000000000000000000000000000000000000000000000000000001200
// ...
// Child 15: 0x0000000000000000000000000000000000000000000000000000000000001f00
uint256 childNodeKey = _params.parentKey.add(childNumber << levelKeyLessSignificantNibble);
uint256 childNodeValue = getRecentNodeAt(self, _params.level, childNodeKey, _params.time);
// Check how many values belong to the subtree of this node. As they are ordered, it will be a contiguous
// subset starting from the beginning, so we only need to know the length of that subset.
uint256 newVisitedTotal = _params.visitedTotal.add(childNodeValue);
uint256 subtreeIncludedValues = _getValuesIncludedInSubtree(_values, _params.foundValues, newVisitedTotal);
// If there are some values included in the subtree of the child node, visit them
if (subtreeIncludedValues > 0) {
// If the child node being analyzed is a leaf, add it to the list of results a number of times equals
// to the number of values that were included in it. Otherwise, descend one level.
if (_params.level == ITEMS_LEVEL) {
_copyFoundNode(_params.foundValues, subtreeIncludedValues, childNodeKey, _resultKeys, childNodeValue, _resultValues);
} else {
SearchParams memory nextLevelParams = SearchParams(
_params.time,
_params.level - 1, // No need for SafeMath: we already checked above that the level being checked is greater than zero
childNodeKey,
_params.foundValues,
_params.visitedTotal
);
_search(self, _values, nextLevelParams, _resultKeys, _resultValues);
}
// Update the number of values that were already found
_params.foundValues = _params.foundValues.add(subtreeIncludedValues);
}
// Update the visited total for the next node in this level
_params.visitedTotal = newVisitedTotal;
}
}
/**
* @dev Private function to check if a new key can be added to the tree based on the current height of the tree
* @param _currentHeight Current height of the tree to check if it supports adding the given key
* @param _newKey Key willing to be added to the tree with the given current height
* @return True if the current height of the tree should be increased to add the new key, false otherwise.
*/
function _shouldAddLevel(uint256 _currentHeight, uint256 _newKey) private pure returns (bool) {
// Build a mask that will match all the possible keys for the given height. For example:
// Height 1: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0 (up to 16 keys)
// Height 2: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 (up to 32 keys)
// ...
// Height 64: 0x0000000000000000000000000000000000000000000000000000000000000000 (up to 16^64 keys - tree max height)
uint256 shift = _currentHeight.mul(BITS_IN_NIBBLE);
uint256 mask = uint256(-1) << shift;
// Check if the given key can be represented in the tree with the current given height using the mask.
return (_newKey & mask) != 0;
}
/**
* @dev Private function to tell how many values of a list can be found in a subtree
* @param _values List of values being searched in ascending order
* @param _foundValues Number of values that were already found and should be ignore
* @param _subtreeTotal Total sum of the given subtree to check the numbers that are included in it
* @return Number of values in the list that are included in the given subtree
*/
function _getValuesIncludedInSubtree(uint256[] memory _values, uint256 _foundValues, uint256 _subtreeTotal) private pure returns (uint256) {
// Look for all the values that can be found in the given subtree
uint256 i = _foundValues;
while (i < _values.length && _values[i] < _subtreeTotal) {
i++;
}
return i - _foundValues;
}
/**
* @dev Private function to copy a node a given number of times to a results list. This function assumes the given
* results list have enough size to support the requested copy.
* @param _from Index of the results list to start copying the given node
* @param _times Number of times the given node will be copied
* @param _key Key of the node to be copied
* @param _resultKeys Lists of key results to copy the given node key to
* @param _value Value of the node to be copied
* @param _resultValues Lists of value results to copy the given node value to
*/
function _copyFoundNode(
uint256 _from,
uint256 _times,
uint256 _key,
uint256[] memory _resultKeys,
uint256 _value,
uint256[] memory _resultValues
)
private
pure
{
for (uint256 i = 0; i < _times; i++) {
_resultKeys[_from + i] = _key;
_resultValues[_from + i] = _value;
}
}
}
/**
* @title GuardiansTreeSortition - Library to perform guardians sortition over a `HexSumTree`
*/
library GuardiansTreeSortition {
using SafeMath for uint256;
using HexSumTree for HexSumTree.Tree;
string private constant ERROR_INVALID_INTERVAL_SEARCH = "TREE_INVALID_INTERVAL_SEARCH";
string private constant ERROR_SORTITION_LENGTHS_MISMATCH = "TREE_SORTITION_LENGTHS_MISMATCH";
/**
* @dev Search random items in the tree based on certain restrictions
* @param _termRandomness Randomness to compute the seed for the draft
* @param _disputeId Identification number of the dispute to draft guardians for
* @param _termId Current term when the draft is being computed
* @param _selectedGuardians Number of guardians already selected for the draft
* @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft
* @param _roundRequestedGuardians Total number of guardians requested to be drafted
* @param _sortitionIteration Number of sortitions already performed for the given draft
* @return guardiansIds List of guardian ids obtained based on the requested search
* @return guardiansBalances List of active balances for each guardian obtained based on the requested search
*/
function batchedRandomSearch(
HexSumTree.Tree storage tree,
bytes32 _termRandomness,
uint256 _disputeId,
uint64 _termId,
uint256 _selectedGuardians,
uint256 _batchRequestedGuardians,
uint256 _roundRequestedGuardians,
uint256 _sortitionIteration
)
internal
view
returns (uint256[] memory guardiansIds, uint256[] memory guardiansBalances)
{
(uint256 low, uint256 high) = getSearchBatchBounds(
tree,
_termId,
_selectedGuardians,
_batchRequestedGuardians,
_roundRequestedGuardians
);
uint256[] memory balances = _computeSearchRandomBalances(
_termRandomness,
_disputeId,
_sortitionIteration,
_batchRequestedGuardians,
low,
high
);
(guardiansIds, guardiansBalances) = tree.search(balances, _termId);
require(guardiansIds.length == guardiansBalances.length, ERROR_SORTITION_LENGTHS_MISMATCH);
require(guardiansIds.length == _batchRequestedGuardians, ERROR_SORTITION_LENGTHS_MISMATCH);
}
/**
* @dev Get the bounds for a draft batch based on the active balances of the guardians
* @param _termId Term ID of the active balances that will be used to compute the boundaries
* @param _selectedGuardians Number of guardians already selected for the draft
* @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft
* @param _roundRequestedGuardians Total number of guardians requested to be drafted
* @return low Low bound to be used for the sortition to draft the requested number of guardians for the given batch
* @return high High bound to be used for the sortition to draft the requested number of guardians for the given batch
*/
function getSearchBatchBounds(
HexSumTree.Tree storage tree,
uint64 _termId,
uint256 _selectedGuardians,
uint256 _batchRequestedGuardians,
uint256 _roundRequestedGuardians
)
internal
view
returns (uint256 low, uint256 high)
{
uint256 totalActiveBalance = tree.getRecentTotalAt(_termId);
low = _selectedGuardians.mul(totalActiveBalance).div(_roundRequestedGuardians);
uint256 newSelectedGuardians = _selectedGuardians.add(_batchRequestedGuardians);
high = newSelectedGuardians.mul(totalActiveBalance).div(_roundRequestedGuardians);
}
/**
* @dev Get a random list of active balances to be searched in the guardians tree for a given draft batch
* @param _termRandomness Randomness to compute the seed for the draft
* @param _disputeId Identification number of the dispute to draft guardians for (for randomness)
* @param _sortitionIteration Number of sortitions already performed for the given draft (for randomness)
* @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft
* @param _lowBatchBound Low bound to be used for the sortition batch to draft the requested number of guardians
* @param _highBatchBound High bound to be used for the sortition batch to draft the requested number of guardians
* @return Random list of active balances to be searched in the guardians tree for the given draft batch
*/
function _computeSearchRandomBalances(
bytes32 _termRandomness,
uint256 _disputeId,
uint256 _sortitionIteration,
uint256 _batchRequestedGuardians,
uint256 _lowBatchBound,
uint256 _highBatchBound
)
internal
pure
returns (uint256[] memory)
{
// Calculate the interval to be used to search the balances in the tree. Since we are using a modulo function to compute the
// random balances to be searched, intervals will be closed on the left and open on the right, for example [0,10).
require(_highBatchBound > _lowBatchBound, ERROR_INVALID_INTERVAL_SEARCH);
uint256 interval = _highBatchBound - _lowBatchBound;
// Compute an ordered list of random active balance to be searched in the guardians tree
uint256[] memory balances = new uint256[](_batchRequestedGuardians);
for (uint256 batchGuardianNumber = 0; batchGuardianNumber < _batchRequestedGuardians; batchGuardianNumber++) {
// Compute a random seed using:
// - The inherent randomness associated to the term from blockhash
// - The disputeId, so 2 disputes in the same term will have different outcomes
// - The sortition iteration, to avoid getting stuck if resulting guardians are dismissed due to locked balance
// - The guardian number in this batch
bytes32 seed = keccak256(abi.encodePacked(_termRandomness, _disputeId, _sortitionIteration, batchGuardianNumber));
// Compute a random active balance to be searched in the guardians tree using the generated seed within the
// boundaries computed for the current batch.
balances[batchGuardianNumber] = _lowBatchBound.add(uint256(seed) % interval);
// Make sure it's ordered, flip values if necessary
for (uint256 i = batchGuardianNumber; i > 0 && balances[i] < balances[i - 1]; i--) {
uint256 tmp = balances[i - 1];
balances[i - 1] = balances[i];
balances[i] = tmp;
}
}
return balances;
}
}
/*
* SPDX-License-Identifier: MIT
*/
interface ILockManager {
/**
* @dev Tell whether a user can unlock a certain amount of tokens
*/
function canUnlock(address user, uint256 amount) external view returns (bool);
}
/*
* SPDX-License-Identifier: MIT
*/
interface IGuardiansRegistry {
/**
* @dev Assign a requested amount of guardian tokens to a guardian
* @param _guardian Guardian to add an amount of tokens to
* @param _amount Amount of tokens to be added to the available balance of a guardian
*/
function assignTokens(address _guardian, uint256 _amount) external;
/**
* @dev Burn a requested amount of guardian tokens
* @param _amount Amount of tokens to be burned
*/
function burnTokens(uint256 _amount) external;
/**
* @dev Draft a set of guardians based on given requirements for a term id
* @param _params Array containing draft requirements:
* 0. bytes32 Term randomness
* 1. uint256 Dispute id
* 2. uint64 Current term id
* 3. uint256 Number of seats already filled
* 4. uint256 Number of seats left to be filled
* 5. uint64 Number of guardians required for the draft
* 6. uint16 Permyriad of the minimum active balance to be locked for the draft
*
* @return guardians List of guardians selected for the draft
* @return length Size of the list of the draft result
*/
function draft(uint256[7] calldata _params) external returns (address[] memory guardians, uint256 length);
/**
* @dev Slash a set of guardians based on their votes compared to the winning ruling
* @param _termId Current term id
* @param _guardians List of guardian addresses to be slashed
* @param _lockedAmounts List of amounts locked for each corresponding guardian that will be either slashed or returned
* @param _rewardedGuardians List of booleans to tell whether a guardian's active balance has to be slashed or not
* @return Total amount of slashed tokens
*/
function slashOrUnlock(uint64 _termId, address[] calldata _guardians, uint256[] calldata _lockedAmounts, bool[] calldata _rewardedGuardians)
external
returns (uint256 collectedTokens);
/**
* @dev Try to collect a certain amount of tokens from a guardian for the next term
* @param _guardian Guardian to collect the tokens from
* @param _amount Amount of tokens to be collected from the given guardian and for the requested term id
* @param _termId Current term id
* @return True if the guardian has enough unlocked tokens to be collected for the requested term, false otherwise
*/
function collectTokens(address _guardian, uint256 _amount, uint64 _termId) external returns (bool);
/**
* @dev Lock a guardian's withdrawals until a certain term ID
* @param _guardian Address of the guardian to be locked
* @param _termId Term ID until which the guardian's withdrawals will be locked
*/
function lockWithdrawals(address _guardian, uint64 _termId) external;
/**
* @dev Tell the active balance of a guardian for a given term id
* @param _guardian Address of the guardian querying the active balance of
* @param _termId Term ID querying the active balance for
* @return Amount of active tokens for guardian in the requested past term id
*/
function activeBalanceOfAt(address _guardian, uint64 _termId) external view returns (uint256);
/**
* @dev Tell the total amount of active guardian tokens at the given term id
* @param _termId Term ID querying the total active balance for
* @return Total amount of active guardian tokens at the given term id
*/
function totalActiveBalanceAt(uint64 _termId) external view returns (uint256);
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/IsContract.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
contract IsContract {
/*
* NOTE: this should NEVER be used for authentication
* (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize).
*
* This is only intended to be used as a sanity check that an address is actually a contract,
* RATHER THAN an address not being a contract.
*/
function isContract(address _target) internal view returns (bool) {
if (_target == address(0)) {
return false;
}
uint256 size;
assembly { size := extcodesize(_target) }
return size > 0;
}
}
contract ACL {
string private constant ERROR_BAD_FREEZE = "ACL_BAD_FREEZE";
string private constant ERROR_ROLE_ALREADY_FROZEN = "ACL_ROLE_ALREADY_FROZEN";
string private constant ERROR_INVALID_BULK_INPUT = "ACL_INVALID_BULK_INPUT";
enum BulkOp { Grant, Revoke, Freeze }
address internal constant FREEZE_FLAG = address(1);
address internal constant ANY_ADDR = address(-1);
// List of all roles assigned to different addresses
mapping (bytes32 => mapping (address => bool)) public roles;
event Granted(bytes32 indexed id, address indexed who);
event Revoked(bytes32 indexed id, address indexed who);
event Frozen(bytes32 indexed id);
/**
* @dev Tell whether an address has a role assigned
* @param _who Address being queried
* @param _id ID of the role being checked
* @return True if the requested address has assigned the given role, false otherwise
*/
function hasRole(address _who, bytes32 _id) public view returns (bool) {
return roles[_id][_who] || roles[_id][ANY_ADDR];
}
/**
* @dev Tell whether a role is frozen
* @param _id ID of the role being checked
* @return True if the given role is frozen, false otherwise
*/
function isRoleFrozen(bytes32 _id) public view returns (bool) {
return roles[_id][FREEZE_FLAG];
}
/**
* @dev Internal function to grant a role to a given address
* @param _id ID of the role to be granted
* @param _who Address to grant the role to
*/
function _grant(bytes32 _id, address _who) internal {
require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN);
require(_who != FREEZE_FLAG, ERROR_BAD_FREEZE);
if (!hasRole(_who, _id)) {
roles[_id][_who] = true;
emit Granted(_id, _who);
}
}
/**
* @dev Internal function to revoke a role from a given address
* @param _id ID of the role to be revoked
* @param _who Address to revoke the role from
*/
function _revoke(bytes32 _id, address _who) internal {
require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN);
if (hasRole(_who, _id)) {
roles[_id][_who] = false;
emit Revoked(_id, _who);
}
}
/**
* @dev Internal function to freeze a role
* @param _id ID of the role to be frozen
*/
function _freeze(bytes32 _id) internal {
require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN);
roles[_id][FREEZE_FLAG] = true;
emit Frozen(_id);
}
/**
* @dev Internal function to enact a bulk list of ACL operations
*/
function _bulk(BulkOp[] memory _op, bytes32[] memory _id, address[] memory _who) internal {
require(_op.length == _id.length && _op.length == _who.length, ERROR_INVALID_BULK_INPUT);
for (uint256 i = 0; i < _op.length; i++) {
BulkOp op = _op[i];
if (op == BulkOp.Grant) {
_grant(_id[i], _who[i]);
} else if (op == BulkOp.Revoke) {
_revoke(_id[i], _who[i]);
} else if (op == BulkOp.Freeze) {
_freeze(_id[i]);
}
}
}
}
contract ModuleIds {
// DisputeManager module ID - keccak256(abi.encodePacked("DISPUTE_MANAGER"))
bytes32 internal constant MODULE_ID_DISPUTE_MANAGER = 0x14a6c70f0f6d449c014c7bbc9e68e31e79e8474fb03b7194df83109a2d888ae6;
// GuardiansRegistry module ID - keccak256(abi.encodePacked("GUARDIANS_REGISTRY"))
bytes32 internal constant MODULE_ID_GUARDIANS_REGISTRY = 0x8af7b7118de65da3b974a3fd4b0c702b66442f74b9dff6eaed1037254c0b79fe;
// Voting module ID - keccak256(abi.encodePacked("VOTING"))
bytes32 internal constant MODULE_ID_VOTING = 0x7cbb12e82a6d63ff16fe43977f43e3e2b247ecd4e62c0e340da8800a48c67346;
// PaymentsBook module ID - keccak256(abi.encodePacked("PAYMENTS_BOOK"))
bytes32 internal constant MODULE_ID_PAYMENTS_BOOK = 0xfa275b1417437a2a2ea8e91e9fe73c28eaf0a28532a250541da5ac0d1892b418;
// Treasury module ID - keccak256(abi.encodePacked("TREASURY"))
bytes32 internal constant MODULE_ID_TREASURY = 0x06aa03964db1f7257357ef09714a5f0ca3633723df419e97015e0c7a3e83edb7;
}
interface IModulesLinker {
/**
* @notice Update the implementations of a list of modules
* @param _ids List of IDs of the modules to be updated
* @param _addresses List of module addresses to be updated
*/
function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external;
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath64.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
/**
* @title SafeMath64
* @dev Math operations for uint64 with safety checks that revert on error
*/
library SafeMath64 {
string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO";
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint64 _a, uint64 _b) internal pure returns (uint64) {
uint256 c = uint256(_a) * uint256(_b);
require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way)
return uint64(c);
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint64 _a, uint64 _b) internal pure returns (uint64) {
require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0
uint64 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint64 _a, uint64 _b) internal pure returns (uint64) {
require(_b <= _a, ERROR_SUB_UNDERFLOW);
uint64 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint64 _a, uint64 _b) internal pure returns (uint64) {
uint64 c = _a + _b;
require(c >= _a, ERROR_ADD_OVERFLOW);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint64 a, uint64 b) internal pure returns (uint64) {
require(b != 0, ERROR_DIV_ZERO);
return a % b;
}
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/Uint256Helpers.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
library Uint256Helpers {
uint256 private constant MAX_UINT8 = uint8(-1);
uint256 private constant MAX_UINT64 = uint64(-1);
string private constant ERROR_UINT8_NUMBER_TOO_BIG = "UINT8_NUMBER_TOO_BIG";
string private constant ERROR_UINT64_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
function toUint8(uint256 a) internal pure returns (uint8) {
require(a <= MAX_UINT8, ERROR_UINT8_NUMBER_TOO_BIG);
return uint8(a);
}
function toUint64(uint256 a) internal pure returns (uint64) {
require(a <= MAX_UINT64, ERROR_UINT64_NUMBER_TOO_BIG);
return uint64(a);
}
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/TimeHelpers.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
contract TimeHelpers {
using Uint256Helpers for uint256;
/**
* @dev Returns the current block number.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber() internal view returns (uint256) {
return block.number;
}
/**
* @dev Returns the current block number, converted to uint64.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber64() internal view returns (uint64) {
return getBlockNumber().toUint64();
}
/**
* @dev Returns the current timestamp.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp() internal view returns (uint256) {
return block.timestamp; // solium-disable-line security/no-block-members
}
/**
* @dev Returns the current timestamp, converted to uint64.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp64() internal view returns (uint64) {
return getTimestamp().toUint64();
}
}
interface IClock {
/**
* @dev Ensure that the current term of the clock is up-to-date
* @return Identification number of the current term
*/
function ensureCurrentTerm() external returns (uint64);
/**
* @dev Transition up to a certain number of terms to leave the clock up-to-date
* @param _maxRequestedTransitions Max number of term transitions allowed by the sender
* @return Identification number of the term ID after executing the heartbeat transitions
*/
function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64);
/**
* @dev Ensure that a certain term has its randomness set
* @return Randomness of the current term
*/
function ensureCurrentTermRandomness() external returns (bytes32);
/**
* @dev Tell the last ensured term identification number
* @return Identification number of the last ensured term
*/
function getLastEnsuredTermId() external view returns (uint64);
/**
* @dev Tell the current term identification number. Note that there may be pending term transitions.
* @return Identification number of the current term
*/
function getCurrentTermId() external view returns (uint64);
/**
* @dev Tell the number of terms the clock should transition to be up-to-date
* @return Number of terms the clock should transition to be up-to-date
*/
function getNeededTermTransitions() external view returns (uint64);
/**
* @dev Tell the information related to a term based on its ID
* @param _termId ID of the term being queried
* @return startTime Term start time
* @return randomnessBN Block number used for randomness in the requested term
* @return randomness Randomness computed for the requested term
*/
function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness);
/**
* @dev Tell the randomness of a term even if it wasn't computed yet
* @param _termId Identification number of the term being queried
* @return Randomness of the requested term
*/
function getTermRandomness(uint64 _termId) external view returns (bytes32);
}
contract CourtClock is IClock, TimeHelpers {
using SafeMath64 for uint64;
string private constant ERROR_TERM_DOES_NOT_EXIST = "CLK_TERM_DOES_NOT_EXIST";
string private constant ERROR_TERM_DURATION_TOO_LONG = "CLK_TERM_DURATION_TOO_LONG";
string private constant ERROR_TERM_RANDOMNESS_NOT_YET = "CLK_TERM_RANDOMNESS_NOT_YET";
string private constant ERROR_TERM_RANDOMNESS_UNAVAILABLE = "CLK_TERM_RANDOMNESS_UNAVAILABLE";
string private constant ERROR_BAD_FIRST_TERM_START_TIME = "CLK_BAD_FIRST_TERM_START_TIME";
string private constant ERROR_TOO_MANY_TRANSITIONS = "CLK_TOO_MANY_TRANSITIONS";
string private constant ERROR_INVALID_TRANSITION_TERMS = "CLK_INVALID_TRANSITION_TERMS";
string private constant ERROR_CANNOT_DELAY_STARTED_COURT = "CLK_CANNOT_DELAY_STARTED_PROT";
string private constant ERROR_CANNOT_DELAY_PAST_START_TIME = "CLK_CANNOT_DELAY_PAST_START_TIME";
// Maximum number of term transitions a callee may have to assume in order to call certain functions that require the Court being up-to-date
uint64 internal constant MAX_AUTO_TERM_TRANSITIONS_ALLOWED = 1;
// Max duration in seconds that a term can last
uint64 internal constant MAX_TERM_DURATION = 365 days;
// Max time until first term starts since contract is deployed
uint64 internal constant MAX_FIRST_TERM_DELAY_PERIOD = 2 * MAX_TERM_DURATION;
struct Term {
uint64 startTime; // Timestamp when the term started
uint64 randomnessBN; // Block number for entropy
bytes32 randomness; // Entropy from randomnessBN block hash
}
// Duration in seconds for each term of the Court
uint64 private termDuration;
// Last ensured term id
uint64 private termId;
// List of Court terms indexed by id
mapping (uint64 => Term) private terms;
event Heartbeat(uint64 previousTermId, uint64 currentTermId);
event StartTimeDelayed(uint64 previousStartTime, uint64 currentStartTime);
/**
* @dev Ensure a certain term has already been processed
* @param _termId Identification number of the term to be checked
*/
modifier termExists(uint64 _termId) {
require(_termId <= termId, ERROR_TERM_DOES_NOT_EXIST);
_;
}
/**
* @dev Constructor function
* @param _termParams Array containing:
* 0. _termDuration Duration in seconds per term
* 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding)
*/
constructor(uint64[2] memory _termParams) public {
uint64 _termDuration = _termParams[0];
uint64 _firstTermStartTime = _termParams[1];
require(_termDuration < MAX_TERM_DURATION, ERROR_TERM_DURATION_TOO_LONG);
require(_firstTermStartTime >= getTimestamp64() + _termDuration, ERROR_BAD_FIRST_TERM_START_TIME);
require(_firstTermStartTime <= getTimestamp64() + MAX_FIRST_TERM_DELAY_PERIOD, ERROR_BAD_FIRST_TERM_START_TIME);
termDuration = _termDuration;
// No need for SafeMath: we already checked values above
terms[0].startTime = _firstTermStartTime - _termDuration;
}
/**
* @notice Ensure that the current term of the Court is up-to-date. If the Court is outdated by more than `MAX_AUTO_TERM_TRANSITIONS_ALLOWED`
* terms, the heartbeat function must be called manually instead.
* @return Identification number of the current term
*/
function ensureCurrentTerm() external returns (uint64) {
return _ensureCurrentTerm();
}
/**
* @notice Transition up to `_maxRequestedTransitions` terms
* @param _maxRequestedTransitions Max number of term transitions allowed by the sender
* @return Identification number of the term ID after executing the heartbeat transitions
*/
function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64) {
return _heartbeat(_maxRequestedTransitions);
}
/**
* @notice Ensure that a certain term has its randomness set. As we allow to draft disputes requested for previous terms, if there
* were mined more than 256 blocks for the current term, the blockhash of its randomness BN is no longer available, given
* round will be able to be drafted in the following term.
* @return Randomness of the current term
*/
function ensureCurrentTermRandomness() external returns (bytes32) {
// If the randomness for the given term was already computed, return
uint64 currentTermId = termId;
Term storage term = terms[currentTermId];
bytes32 termRandomness = term.randomness;
if (termRandomness != bytes32(0)) {
return termRandomness;
}
// Compute term randomness
bytes32 newRandomness = _computeTermRandomness(currentTermId);
require(newRandomness != bytes32(0), ERROR_TERM_RANDOMNESS_UNAVAILABLE);
term.randomness = newRandomness;
return newRandomness;
}
/**
* @dev Tell the term duration of the Court
* @return Duration in seconds of the Court term
*/
function getTermDuration() external view returns (uint64) {
return termDuration;
}
/**
* @dev Tell the last ensured term identification number
* @return Identification number of the last ensured term
*/
function getLastEnsuredTermId() external view returns (uint64) {
return _lastEnsuredTermId();
}
/**
* @dev Tell the current term identification number. Note that there may be pending term transitions.
* @return Identification number of the current term
*/
function getCurrentTermId() external view returns (uint64) {
return _currentTermId();
}
/**
* @dev Tell the number of terms the Court should transition to be up-to-date
* @return Number of terms the Court should transition to be up-to-date
*/
function getNeededTermTransitions() external view returns (uint64) {
return _neededTermTransitions();
}
/**
* @dev Tell the information related to a term based on its ID. Note that if the term has not been reached, the
* information returned won't be computed yet. This function allows querying future terms that were not computed yet.
* @param _termId ID of the term being queried
* @return startTime Term start time
* @return randomnessBN Block number used for randomness in the requested term
* @return randomness Randomness computed for the requested term
*/
function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness) {
Term storage term = terms[_termId];
return (term.startTime, term.randomnessBN, term.randomness);
}
/**
* @dev Tell the randomness of a term even if it wasn't computed yet
* @param _termId Identification number of the term being queried
* @return Randomness of the requested term
*/
function getTermRandomness(uint64 _termId) external view termExists(_termId) returns (bytes32) {
return _computeTermRandomness(_termId);
}
/**
* @dev Internal function to ensure that the current term of the Court is up-to-date. If the Court is outdated by more than
* `MAX_AUTO_TERM_TRANSITIONS_ALLOWED` terms, the heartbeat function must be called manually.
* @return Identification number of the resultant term ID after executing the corresponding transitions
*/
function _ensureCurrentTerm() internal returns (uint64) {
// Check the required number of transitions does not exceeds the max allowed number to be processed automatically
uint64 requiredTransitions = _neededTermTransitions();
require(requiredTransitions <= MAX_AUTO_TERM_TRANSITIONS_ALLOWED, ERROR_TOO_MANY_TRANSITIONS);
// If there are no transitions pending, return the last ensured term id
if (uint256(requiredTransitions) == 0) {
return termId;
}
// Process transition if there is at least one pending
return _heartbeat(requiredTransitions);
}
/**
* @dev Internal function to transition the Court terms up to a requested number of terms
* @param _maxRequestedTransitions Max number of term transitions allowed by the sender
* @return Identification number of the resultant term ID after executing the requested transitions
*/
function _heartbeat(uint64 _maxRequestedTransitions) internal returns (uint64) {
// Transition the minimum number of terms between the amount requested and the amount actually needed
uint64 neededTransitions = _neededTermTransitions();
uint256 transitions = uint256(_maxRequestedTransitions < neededTransitions ? _maxRequestedTransitions : neededTransitions);
require(transitions > 0, ERROR_INVALID_TRANSITION_TERMS);
uint64 blockNumber = getBlockNumber64();
uint64 previousTermId = termId;
uint64 currentTermId = previousTermId;
for (uint256 transition = 1; transition <= transitions; transition++) {
// Term IDs are incremented by one based on the number of time periods since the Court started. Since time is represented in uint64,
// even if we chose the minimum duration possible for a term (1 second), we can ensure terms will never reach 2^64 since time is
// already assumed to fit in uint64.
Term storage previousTerm = terms[currentTermId++];
Term storage currentTerm = terms[currentTermId];
_onTermTransitioned(currentTermId);
// Set the start time of the new term. Note that we are using a constant term duration value to guarantee
// equally long terms, regardless of heartbeats.
currentTerm.startTime = previousTerm.startTime.add(termDuration);
// In order to draft a random number of guardians in a term, we use a randomness factor for each term based on a
// block number that is set once the term has started. Note that this information could not be known beforehand.
currentTerm.randomnessBN = blockNumber + 1;
}
termId = currentTermId;
emit Heartbeat(previousTermId, currentTermId);
return currentTermId;
}
/**
* @dev Internal function to delay the first term start time only if it wasn't reached yet
* @param _newFirstTermStartTime New timestamp in seconds when the court will open
*/
function _delayStartTime(uint64 _newFirstTermStartTime) internal {
require(_currentTermId() == 0, ERROR_CANNOT_DELAY_STARTED_COURT);
Term storage term = terms[0];
uint64 currentFirstTermStartTime = term.startTime.add(termDuration);
require(_newFirstTermStartTime > currentFirstTermStartTime, ERROR_CANNOT_DELAY_PAST_START_TIME);
// No need for SafeMath: we already checked above that `_newFirstTermStartTime` > `currentFirstTermStartTime` >= `termDuration`
term.startTime = _newFirstTermStartTime - termDuration;
emit StartTimeDelayed(currentFirstTermStartTime, _newFirstTermStartTime);
}
/**
* @dev Internal function to notify when a term has been transitioned. This function must be overridden to provide custom behavior.
* @param _termId Identification number of the new current term that has been transitioned
*/
function _onTermTransitioned(uint64 _termId) internal;
/**
* @dev Internal function to tell the last ensured term identification number
* @return Identification number of the last ensured term
*/
function _lastEnsuredTermId() internal view returns (uint64) {
return termId;
}
/**
* @dev Internal function to tell the current term identification number. Note that there may be pending term transitions.
* @return Identification number of the current term
*/
function _currentTermId() internal view returns (uint64) {
return termId.add(_neededTermTransitions());
}
/**
* @dev Internal function to tell the number of terms the Court should transition to be up-to-date
* @return Number of terms the Court should transition to be up-to-date
*/
function _neededTermTransitions() internal view returns (uint64) {
// Note that the Court is always initialized providing a start time for the first-term in the future. If that's the case,
// no term transitions are required.
uint64 currentTermStartTime = terms[termId].startTime;
if (getTimestamp64() < currentTermStartTime) {
return uint64(0);
}
// No need for SafeMath: we already know that the start time of the current term is in the past
return (getTimestamp64() - currentTermStartTime) / termDuration;
}
/**
* @dev Internal function to compute the randomness that will be used to draft guardians for the given term. This
* function assumes the given term exists. To determine the randomness factor for a term we use the hash of a
* block number that is set once the term has started to ensure it cannot be known beforehand. Note that the
* hash function being used only works for the 256 most recent block numbers.
* @param _termId Identification number of the term being queried
* @return Randomness computed for the given term
*/
function _computeTermRandomness(uint64 _termId) internal view returns (bytes32) {
Term storage term = terms[_termId];
require(getBlockNumber64() > term.randomnessBN, ERROR_TERM_RANDOMNESS_NOT_YET);
return blockhash(term.randomnessBN);
}
}
interface IConfig {
/**
* @dev Tell the full Court configuration parameters at a certain term
* @param _termId Identification number of the term querying the Court config of
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getConfig(uint64 _termId) external view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
);
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct);
/**
* @dev Tell the min active balance config at a certain term
* @param _termId Term querying the min active balance config of
* @return Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getMinActiveBalance(uint64 _termId) external view returns (uint256);
}
contract CourtConfigData {
struct Config {
FeesConfig fees; // Full fees-related config
DisputesConfig disputes; // Full disputes-related config
uint256 minActiveBalance; // Minimum amount of tokens guardians have to activate to participate in the Court
}
struct FeesConfig {
IERC20 token; // ERC20 token to be used for the fees of the Court
uint16 finalRoundReduction; // Permyriad of fees reduction applied for final appeal round (‱ - 1/10,000)
uint256 guardianFee; // Amount of tokens paid to draft a guardian to adjudicate a dispute
uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians
uint256 settleFee; // Amount of tokens paid per round to cover the costs of slashing guardians
}
struct DisputesConfig {
uint64 evidenceTerms; // Max submitting evidence period duration in terms
uint64 commitTerms; // Committing period duration in terms
uint64 revealTerms; // Revealing period duration in terms
uint64 appealTerms; // Appealing period duration in terms
uint64 appealConfirmTerms; // Confirmation appeal period duration in terms
uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
uint64 firstRoundGuardiansNumber; // Number of guardians drafted on first round
uint64 appealStepFactor; // Factor in which the guardians number is increased on each appeal
uint64 finalRoundLockTerms; // Period a coherent guardian in the final round will remain locked
uint256 maxRegularAppealRounds; // Before the final appeal
uint256 appealCollateralFactor; // Permyriad multiple of dispute fees required to appeal a preliminary ruling (‱ - 1/10,000)
uint256 appealConfirmCollateralFactor; // Permyriad multiple of dispute fees required to confirm appeal (‱ - 1/10,000)
}
struct DraftConfig {
IERC20 feeToken; // ERC20 token to be used for the fees of the Court
uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians
}
}
contract CourtConfig is IConfig, CourtConfigData {
using SafeMath64 for uint64;
using PctHelpers for uint256;
string private constant ERROR_TOO_OLD_TERM = "CONF_TOO_OLD_TERM";
string private constant ERROR_INVALID_PENALTY_PCT = "CONF_INVALID_PENALTY_PCT";
string private constant ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT = "CONF_INVALID_FINAL_ROUND_RED_PCT";
string private constant ERROR_INVALID_MAX_APPEAL_ROUNDS = "CONF_INVALID_MAX_APPEAL_ROUNDS";
string private constant ERROR_LARGE_ROUND_PHASE_DURATION = "CONF_LARGE_ROUND_PHASE_DURATION";
string private constant ERROR_BAD_INITIAL_GUARDIANS_NUMBER = "CONF_BAD_INITIAL_GUARDIAN_NUMBER";
string private constant ERROR_BAD_APPEAL_STEP_FACTOR = "CONF_BAD_APPEAL_STEP_FACTOR";
string private constant ERROR_ZERO_COLLATERAL_FACTOR = "CONF_ZERO_COLLATERAL_FACTOR";
string private constant ERROR_ZERO_MIN_ACTIVE_BALANCE = "CONF_ZERO_MIN_ACTIVE_BALANCE";
// Max number of terms that each of the different adjudication states can last (if lasted 1h, this would be a year)
uint64 internal constant MAX_ADJ_STATE_DURATION = 8670;
// Cap the max number of regular appeal rounds
uint256 internal constant MAX_REGULAR_APPEAL_ROUNDS_LIMIT = 10;
// Future term ID in which a config change has been scheduled
uint64 private configChangeTermId;
// List of all the configs used in the Court
Config[] private configs;
// List of configs indexed by id
mapping (uint64 => uint256) private configIdByTerm;
event NewConfig(uint64 fromTermId, uint64 courtConfigId);
/**
* @dev Constructor function
* @param _feeToken Address of the token contract that is used to pay for fees
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
constructor(
IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance
)
public
{
// Leave config at index 0 empty for non-scheduled config changes
configs.length = 1;
_setConfig(
0,
0,
_feeToken,
_fees,
_roundStateDurations,
_pcts,
_roundParams,
_appealCollateralParams,
_minActiveBalance
);
}
/**
* @dev Tell the full Court configuration parameters at a certain term
* @param _termId Identification number of the term querying the Court config of
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getConfig(uint64 _termId) external view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
);
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct);
/**
* @dev Tell the min active balance config at a certain term
* @param _termId Term querying the min active balance config of
* @return Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getMinActiveBalance(uint64 _termId) external view returns (uint256);
/**
* @dev Tell the term identification number of the next scheduled config change
* @return Term identification number of the next scheduled config change
*/
function getConfigChangeTermId() external view returns (uint64) {
return configChangeTermId;
}
/**
* @dev Internal to make sure to set a config for the new term, it will copy the previous term config if none
* @param _termId Identification number of the new current term that has been transitioned
*/
function _ensureTermConfig(uint64 _termId) internal {
// If the term being transitioned had no config change scheduled, keep the previous one
uint256 currentConfigId = configIdByTerm[_termId];
if (currentConfigId == 0) {
uint256 previousConfigId = configIdByTerm[_termId.sub(1)];
configIdByTerm[_termId] = previousConfigId;
}
}
/**
* @dev Assumes that sender it's allowed (either it's from governor or it's on init)
* @param _termId Identification number of the current Court term
* @param _fromTermId Identification number of the term in which the config will be effective at
* @param _feeToken Address of the token contract that is used to pay for fees.
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
function _setConfig(
uint64 _termId,
uint64 _fromTermId,
IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance
)
internal
{
// If the current term is not zero, changes must be scheduled at least after the current period.
// No need to ensure delays for on-going disputes since these already use their creation term for that.
require(_termId == 0 || _fromTermId > _termId, ERROR_TOO_OLD_TERM);
// Make sure appeal collateral factors are greater than zero
require(_appealCollateralParams[0] > 0 && _appealCollateralParams[1] > 0, ERROR_ZERO_COLLATERAL_FACTOR);
// Make sure the given penalty and final round reduction pcts are not greater than 100%
require(PctHelpers.isValid(_pcts[0]), ERROR_INVALID_PENALTY_PCT);
require(PctHelpers.isValid(_pcts[1]), ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT);
// Disputes must request at least one guardian to be drafted initially
require(_roundParams[0] > 0, ERROR_BAD_INITIAL_GUARDIANS_NUMBER);
// Prevent that further rounds have zero guardians
require(_roundParams[1] > 0, ERROR_BAD_APPEAL_STEP_FACTOR);
// Make sure the max number of appeals allowed does not reach the limit
uint256 _maxRegularAppealRounds = _roundParams[2];
bool isMaxAppealRoundsValid = _maxRegularAppealRounds > 0 && _maxRegularAppealRounds <= MAX_REGULAR_APPEAL_ROUNDS_LIMIT;
require(isMaxAppealRoundsValid, ERROR_INVALID_MAX_APPEAL_ROUNDS);
// Make sure each adjudication round phase duration is valid
for (uint i = 0; i < _roundStateDurations.length; i++) {
require(_roundStateDurations[i] > 0 && _roundStateDurations[i] < MAX_ADJ_STATE_DURATION, ERROR_LARGE_ROUND_PHASE_DURATION);
}
// Make sure min active balance is not zero
require(_minActiveBalance > 0, ERROR_ZERO_MIN_ACTIVE_BALANCE);
// If there was a config change already scheduled, reset it (in that case we will overwrite last array item).
// Otherwise, schedule a new config.
if (configChangeTermId > _termId) {
configIdByTerm[configChangeTermId] = 0;
} else {
configs.length++;
}
uint64 courtConfigId = uint64(configs.length - 1);
Config storage config = configs[courtConfigId];
config.fees = FeesConfig({
token: _feeToken,
guardianFee: _fees[0],
draftFee: _fees[1],
settleFee: _fees[2],
finalRoundReduction: _pcts[1]
});
config.disputes = DisputesConfig({
evidenceTerms: _roundStateDurations[0],
commitTerms: _roundStateDurations[1],
revealTerms: _roundStateDurations[2],
appealTerms: _roundStateDurations[3],
appealConfirmTerms: _roundStateDurations[4],
penaltyPct: _pcts[0],
firstRoundGuardiansNumber: _roundParams[0],
appealStepFactor: _roundParams[1],
maxRegularAppealRounds: _maxRegularAppealRounds,
finalRoundLockTerms: _roundParams[3],
appealCollateralFactor: _appealCollateralParams[0],
appealConfirmCollateralFactor: _appealCollateralParams[1]
});
config.minActiveBalance = _minActiveBalance;
configIdByTerm[_fromTermId] = courtConfigId;
configChangeTermId = _fromTermId;
emit NewConfig(_fromTermId, courtConfigId);
}
/**
* @dev Internal function to get the Court config for a given term
* @param _termId Identification number of the term querying the Court config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @return minActiveBalance Minimum amount of guardian tokens that can be activated
*/
function _getConfigAt(uint64 _termId, uint64 _lastEnsuredTermId) internal view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
)
{
Config storage config = _getConfigFor(_termId, _lastEnsuredTermId);
FeesConfig storage feesConfig = config.fees;
feeToken = feesConfig.token;
fees = [feesConfig.guardianFee, feesConfig.draftFee, feesConfig.settleFee];
DisputesConfig storage disputesConfig = config.disputes;
roundStateDurations = [
disputesConfig.evidenceTerms,
disputesConfig.commitTerms,
disputesConfig.revealTerms,
disputesConfig.appealTerms,
disputesConfig.appealConfirmTerms
];
pcts = [disputesConfig.penaltyPct, feesConfig.finalRoundReduction];
roundParams = [
disputesConfig.firstRoundGuardiansNumber,
disputesConfig.appealStepFactor,
uint64(disputesConfig.maxRegularAppealRounds),
disputesConfig.finalRoundLockTerms
];
appealCollateralParams = [disputesConfig.appealCollateralFactor, disputesConfig.appealConfirmCollateralFactor];
minActiveBalance = config.minActiveBalance;
}
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function _getDraftConfig(uint64 _termId, uint64 _lastEnsuredTermId) internal view
returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct)
{
Config storage config = _getConfigFor(_termId, _lastEnsuredTermId);
return (config.fees.token, config.fees.draftFee, config.disputes.penaltyPct);
}
/**
* @dev Internal function to get the min active balance config for a given term
* @param _termId Identification number of the term querying the min active balance config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return Minimum amount of guardian tokens that can be activated at the given term
*/
function _getMinActiveBalance(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) {
Config storage config = _getConfigFor(_termId, _lastEnsuredTermId);
return config.minActiveBalance;
}
/**
* @dev Internal function to get the Court config for a given term
* @param _termId Identification number of the term querying the min active balance config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return Court config for the given term
*/
function _getConfigFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (Config storage) {
uint256 id = _getConfigIdFor(_termId, _lastEnsuredTermId);
return configs[id];
}
/**
* @dev Internal function to get the Court config ID for a given term
* @param _termId Identification number of the term querying the Court config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return Identification number of the config for the given terms
*/
function _getConfigIdFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) {
// If the given term is lower or equal to the last ensured Court term, it is safe to use a past Court config
if (_termId <= _lastEnsuredTermId) {
return configIdByTerm[_termId];
}
// If the given term is in the future but there is a config change scheduled before it, use the incoming config
uint64 scheduledChangeTermId = configChangeTermId;
if (scheduledChangeTermId <= _termId) {
return configIdByTerm[scheduledChangeTermId];
}
// If no changes are scheduled, use the Court config of the last ensured term
return configIdByTerm[_lastEnsuredTermId];
}
}
/*
* SPDX-License-Identifier: MIT
*/
interface IArbitrator {
/**
* @dev Create a dispute over the Arbitrable sender with a number of possible rulings
* @param _possibleRulings Number of possible rulings allowed for the dispute
* @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created
* @return Dispute identification number
*/
function createDispute(uint256 _possibleRulings, bytes calldata _metadata) external returns (uint256);
/**
* @dev Submit evidence for a dispute
* @param _disputeId Id of the dispute in the Court
* @param _submitter Address of the account submitting the evidence
* @param _evidence Data submitted for the evidence related to the dispute
*/
function submitEvidence(uint256 _disputeId, address _submitter, bytes calldata _evidence) external;
/**
* @dev Close the evidence period of a dispute
* @param _disputeId Identification number of the dispute to close its evidence submitting period
*/
function closeEvidencePeriod(uint256 _disputeId) external;
/**
* @notice Rule dispute #`_disputeId` if ready
* @param _disputeId Identification number of the dispute to be ruled
* @return subject Subject associated to the dispute
* @return ruling Ruling number computed for the given dispute
*/
function rule(uint256 _disputeId) external returns (address subject, uint256 ruling);
/**
* @dev Tell the dispute fees information to create a dispute
* @return recipient Address where the corresponding dispute fees must be transferred to
* @return feeToken ERC20 token used for the fees
* @return feeAmount Total amount of fees that must be allowed to the recipient
*/
function getDisputeFees() external view returns (address recipient, IERC20 feeToken, uint256 feeAmount);
/**
* @dev Tell the payments recipient address
* @return Address of the payments recipient module
*/
function getPaymentsRecipient() external view returns (address);
}
/*
* SPDX-License-Identifier: MIT
*/
/**
* @dev The Arbitrable instances actually don't require to follow any specific interface.
* Note that this is actually optional, although it does allow the Court to at least have a way to identify a specific set of instances.
*/
contract IArbitrable {
/**
* @dev Emitted when an IArbitrable instance's dispute is ruled by an IArbitrator
* @param arbitrator IArbitrator instance ruling the dispute
* @param disputeId Identification number of the dispute being ruled by the arbitrator
* @param ruling Ruling given by the arbitrator
*/
event Ruled(IArbitrator indexed arbitrator, uint256 indexed disputeId, uint256 ruling);
}
interface IDisputeManager {
enum DisputeState {
PreDraft,
Adjudicating,
Ruled
}
enum AdjudicationState {
Invalid,
Committing,
Revealing,
Appealing,
ConfirmingAppeal,
Ended
}
/**
* @dev Create a dispute to be drafted in a future term
* @param _subject Arbitrable instance creating the dispute
* @param _possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute
* @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created
* @return Dispute identification number
*/
function createDispute(IArbitrable _subject, uint8 _possibleRulings, bytes calldata _metadata) external returns (uint256);
/**
* @dev Submit evidence for a dispute
* @param _subject Arbitrable instance submitting the dispute
* @param _disputeId Identification number of the dispute receiving new evidence
* @param _submitter Address of the account submitting the evidence
* @param _evidence Data submitted for the evidence of the dispute
*/
function submitEvidence(IArbitrable _subject, uint256 _disputeId, address _submitter, bytes calldata _evidence) external;
/**
* @dev Close the evidence period of a dispute
* @param _subject IArbitrable instance requesting to close the evidence submission period
* @param _disputeId Identification number of the dispute to close its evidence submitting period
*/
function closeEvidencePeriod(IArbitrable _subject, uint256 _disputeId) external;
/**
* @dev Draft guardians for the next round of a dispute
* @param _disputeId Identification number of the dispute to be drafted
*/
function draft(uint256 _disputeId) external;
/**
* @dev Appeal round of a dispute in favor of a certain ruling
* @param _disputeId Identification number of the dispute being appealed
* @param _roundId Identification number of the dispute round being appealed
* @param _ruling Ruling appealing a dispute round in favor of
*/
function createAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external;
/**
* @dev Confirm appeal for a round of a dispute in favor of a ruling
* @param _disputeId Identification number of the dispute confirming an appeal of
* @param _roundId Identification number of the dispute round confirming an appeal of
* @param _ruling Ruling being confirmed against a dispute round appeal
*/
function confirmAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external;
/**
* @dev Compute the final ruling for a dispute
* @param _disputeId Identification number of the dispute to compute its final ruling
* @return subject Arbitrable instance associated to the dispute
* @return finalRuling Final ruling decided for the given dispute
*/
function computeRuling(uint256 _disputeId) external returns (IArbitrable subject, uint8 finalRuling);
/**
* @dev Settle penalties for a round of a dispute
* @param _disputeId Identification number of the dispute to settle penalties for
* @param _roundId Identification number of the dispute round to settle penalties for
* @param _guardiansToSettle Maximum number of guardians to be slashed in this call
*/
function settlePenalties(uint256 _disputeId, uint256 _roundId, uint256 _guardiansToSettle) external;
/**
* @dev Claim rewards for a round of a dispute for guardian
* @dev For regular rounds, it will only reward winning guardians
* @param _disputeId Identification number of the dispute to settle rewards for
* @param _roundId Identification number of the dispute round to settle rewards for
* @param _guardian Address of the guardian to settle their rewards
*/
function settleReward(uint256 _disputeId, uint256 _roundId, address _guardian) external;
/**
* @dev Settle appeal deposits for a round of a dispute
* @param _disputeId Identification number of the dispute to settle appeal deposits for
* @param _roundId Identification number of the dispute round to settle appeal deposits for
*/
function settleAppealDeposit(uint256 _disputeId, uint256 _roundId) external;
/**
* @dev Tell the amount of token fees required to create a dispute
* @return feeToken ERC20 token used for the fees
* @return feeAmount Total amount of fees to be paid for a dispute at the given term
*/
function getDisputeFees() external view returns (IERC20 feeToken, uint256 feeAmount);
/**
* @dev Tell information of a certain dispute
* @param _disputeId Identification number of the dispute being queried
* @return subject Arbitrable subject being disputed
* @return possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute
* @return state Current state of the dispute being queried: pre-draft, adjudicating, or ruled
* @return finalRuling The winning ruling in case the dispute is finished
* @return lastRoundId Identification number of the last round created for the dispute
* @return createTermId Identification number of the term when the dispute was created
*/
function getDispute(uint256 _disputeId) external view
returns (IArbitrable subject, uint8 possibleRulings, DisputeState state, uint8 finalRuling, uint256 lastRoundId, uint64 createTermId);
/**
* @dev Tell information of a certain adjudication round
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round being queried
* @return draftTerm Term from which the requested round can be drafted
* @return delayedTerms Number of terms the given round was delayed based on its requested draft term id
* @return guardiansNumber Number of guardians requested for the round
* @return selectedGuardians Number of guardians already selected for the requested round
* @return settledPenalties Whether or not penalties have been settled for the requested round
* @return collectedTokens Amount of guardian tokens that were collected from slashed guardians for the requested round
* @return coherentGuardians Number of guardians that voted in favor of the final ruling in the requested round
* @return state Adjudication state of the requested round
*/
function getRound(uint256 _disputeId, uint256 _roundId) external view
returns (
uint64 draftTerm,
uint64 delayedTerms,
uint64 guardiansNumber,
uint64 selectedGuardians,
uint256 guardianFees,
bool settledPenalties,
uint256 collectedTokens,
uint64 coherentGuardians,
AdjudicationState state
);
/**
* @dev Tell appeal-related information of a certain adjudication round
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round being queried
* @return maker Address of the account appealing the given round
* @return appealedRuling Ruling confirmed by the appealer of the given round
* @return taker Address of the account confirming the appeal of the given round
* @return opposedRuling Ruling confirmed by the appeal taker of the given round
*/
function getAppeal(uint256 _disputeId, uint256 _roundId) external view
returns (address maker, uint64 appealedRuling, address taker, uint64 opposedRuling);
/**
* @dev Tell information related to the next round due to an appeal of a certain round given.
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round requesting the appeal details of
* @return nextRoundStartTerm Term ID from which the next round will start
* @return nextRoundGuardiansNumber Guardians number for the next round
* @return newDisputeState New state for the dispute associated to the given round after the appeal
* @return feeToken ERC20 token used for the next round fees
* @return guardianFees Total amount of fees to be distributed between the winning guardians of the next round
* @return totalFees Total amount of fees for a regular round at the given term
* @return appealDeposit Amount to be deposit of fees for a regular round at the given term
* @return confirmAppealDeposit Total amount of fees for a regular round at the given term
*/
function getNextRoundDetails(uint256 _disputeId, uint256 _roundId) external view
returns (
uint64 nextRoundStartTerm,
uint64 nextRoundGuardiansNumber,
DisputeState newDisputeState,
IERC20 feeToken,
uint256 totalFees,
uint256 guardianFees,
uint256 appealDeposit,
uint256 confirmAppealDeposit
);
/**
* @dev Tell guardian-related information of a certain adjudication round
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round being queried
* @param _guardian Address of the guardian being queried
* @return weight Guardian weight drafted for the requested round
* @return rewarded Whether or not the given guardian was rewarded based on the requested round
*/
function getGuardian(uint256 _disputeId, uint256 _roundId, address _guardian) external view returns (uint64 weight, bool rewarded);
}
contract Controller is IsContract, ModuleIds, CourtClock, CourtConfig, ACL {
string private constant ERROR_SENDER_NOT_GOVERNOR = "CTR_SENDER_NOT_GOVERNOR";
string private constant ERROR_INVALID_GOVERNOR_ADDRESS = "CTR_INVALID_GOVERNOR_ADDRESS";
string private constant ERROR_MODULE_NOT_SET = "CTR_MODULE_NOT_SET";
string private constant ERROR_MODULE_ALREADY_ENABLED = "CTR_MODULE_ALREADY_ENABLED";
string private constant ERROR_MODULE_ALREADY_DISABLED = "CTR_MODULE_ALREADY_DISABLED";
string private constant ERROR_DISPUTE_MANAGER_NOT_ACTIVE = "CTR_DISPUTE_MANAGER_NOT_ACTIVE";
string private constant ERROR_CUSTOM_FUNCTION_NOT_SET = "CTR_CUSTOM_FUNCTION_NOT_SET";
string private constant ERROR_IMPLEMENTATION_NOT_CONTRACT = "CTR_IMPLEMENTATION_NOT_CONTRACT";
string private constant ERROR_INVALID_IMPLS_INPUT_LENGTH = "CTR_INVALID_IMPLS_INPUT_LENGTH";
address private constant ZERO_ADDRESS = address(0);
/**
* @dev Governor of the whole system. Set of three addresses to recover funds, change configuration settings and setup modules
*/
struct Governor {
address funds; // This address can be unset at any time. It is allowed to recover funds from the ControlledRecoverable modules
address config; // This address is meant not to be unset. It is allowed to change the different configurations of the whole system
address modules; // This address can be unset at any time. It is allowed to plug/unplug modules from the system
}
/**
* @dev Module information
*/
struct Module {
bytes32 id; // ID associated to a module
bool disabled; // Whether the module is disabled
}
// Governor addresses of the system
Governor private governor;
// List of current modules registered for the system indexed by ID
mapping (bytes32 => address) internal currentModules;
// List of all historical modules registered for the system indexed by address
mapping (address => Module) internal allModules;
// List of custom function targets indexed by signature
mapping (bytes4 => address) internal customFunctions;
event ModuleSet(bytes32 id, address addr);
event ModuleEnabled(bytes32 id, address addr);
event ModuleDisabled(bytes32 id, address addr);
event CustomFunctionSet(bytes4 signature, address target);
event FundsGovernorChanged(address previousGovernor, address currentGovernor);
event ConfigGovernorChanged(address previousGovernor, address currentGovernor);
event ModulesGovernorChanged(address previousGovernor, address currentGovernor);
/**
* @dev Ensure the msg.sender is the funds governor
*/
modifier onlyFundsGovernor {
require(msg.sender == governor.funds, ERROR_SENDER_NOT_GOVERNOR);
_;
}
/**
* @dev Ensure the msg.sender is the modules governor
*/
modifier onlyConfigGovernor {
require(msg.sender == governor.config, ERROR_SENDER_NOT_GOVERNOR);
_;
}
/**
* @dev Ensure the msg.sender is the modules governor
*/
modifier onlyModulesGovernor {
require(msg.sender == governor.modules, ERROR_SENDER_NOT_GOVERNOR);
_;
}
/**
* @dev Ensure the given dispute manager is active
*/
modifier onlyActiveDisputeManager(IDisputeManager _disputeManager) {
require(!_isModuleDisabled(address(_disputeManager)), ERROR_DISPUTE_MANAGER_NOT_ACTIVE);
_;
}
/**
* @dev Constructor function
* @param _termParams Array containing:
* 0. _termDuration Duration in seconds per term
* 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding)
* @param _governors Array containing:
* 0. _fundsGovernor Address of the funds governor
* 1. _configGovernor Address of the config governor
* 2. _modulesGovernor Address of the modules governor
* @param _feeToken Address of the token contract that is used to pay for fees
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling
* 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
constructor(
uint64[2] memory _termParams,
address[3] memory _governors,
IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance
)
public
CourtClock(_termParams)
CourtConfig(_feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance)
{
_setFundsGovernor(_governors[0]);
_setConfigGovernor(_governors[1]);
_setModulesGovernor(_governors[2]);
}
/**
* @dev Fallback function allows to forward calls to a specific address in case it was previously registered
* Note the sender will be always the controller in case it is forwarded
*/
function () external payable {
address target = customFunctions[msg.sig];
require(target != address(0), ERROR_CUSTOM_FUNCTION_NOT_SET);
// solium-disable-next-line security/no-call-value
(bool success,) = address(target).call.value(msg.value)(msg.data);
assembly {
let size := returndatasize
let ptr := mload(0x40)
returndatacopy(ptr, 0, size)
let result := success
switch result case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
/**
* @notice Change Court configuration params
* @param _fromTermId Identification number of the term in which the config will be effective at
* @param _feeToken Address of the token contract that is used to pay for fees
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling
* 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
function setConfig(
uint64 _fromTermId,
IERC20 _feeToken,
uint256[3] calldata _fees,
uint64[5] calldata _roundStateDurations,
uint16[2] calldata _pcts,
uint64[4] calldata _roundParams,
uint256[2] calldata _appealCollateralParams,
uint256 _minActiveBalance
)
external
onlyConfigGovernor
{
uint64 currentTermId = _ensureCurrentTerm();
_setConfig(
currentTermId,
_fromTermId,
_feeToken,
_fees,
_roundStateDurations,
_pcts,
_roundParams,
_appealCollateralParams,
_minActiveBalance
);
}
/**
* @notice Delay the Court start time to `_newFirstTermStartTime`
* @param _newFirstTermStartTime New timestamp in seconds when the court will open
*/
function delayStartTime(uint64 _newFirstTermStartTime) external onlyConfigGovernor {
_delayStartTime(_newFirstTermStartTime);
}
/**
* @notice Change funds governor address to `_newFundsGovernor`
* @param _newFundsGovernor Address of the new funds governor to be set
*/
function changeFundsGovernor(address _newFundsGovernor) external onlyFundsGovernor {
require(_newFundsGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS);
_setFundsGovernor(_newFundsGovernor);
}
/**
* @notice Change config governor address to `_newConfigGovernor`
* @param _newConfigGovernor Address of the new config governor to be set
*/
function changeConfigGovernor(address _newConfigGovernor) external onlyConfigGovernor {
require(_newConfigGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS);
_setConfigGovernor(_newConfigGovernor);
}
/**
* @notice Change modules governor address to `_newModulesGovernor`
* @param _newModulesGovernor Address of the new governor to be set
*/
function changeModulesGovernor(address _newModulesGovernor) external onlyModulesGovernor {
require(_newModulesGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS);
_setModulesGovernor(_newModulesGovernor);
}
/**
* @notice Remove the funds governor. Set the funds governor to the zero address.
* @dev This action cannot be rolled back, once the funds governor has been unset, funds cannot be recovered from recoverable modules anymore
*/
function ejectFundsGovernor() external onlyFundsGovernor {
_setFundsGovernor(ZERO_ADDRESS);
}
/**
* @notice Remove the modules governor. Set the modules governor to the zero address.
* @dev This action cannot be rolled back, once the modules governor has been unset, system modules cannot be changed anymore
*/
function ejectModulesGovernor() external onlyModulesGovernor {
_setModulesGovernor(ZERO_ADDRESS);
}
/**
* @notice Grant `_id` role to `_who`
* @param _id ID of the role to be granted
* @param _who Address to grant the role to
*/
function grant(bytes32 _id, address _who) external onlyConfigGovernor {
_grant(_id, _who);
}
/**
* @notice Revoke `_id` role from `_who`
* @param _id ID of the role to be revoked
* @param _who Address to revoke the role from
*/
function revoke(bytes32 _id, address _who) external onlyConfigGovernor {
_revoke(_id, _who);
}
/**
* @notice Freeze `_id` role
* @param _id ID of the role to be frozen
*/
function freeze(bytes32 _id) external onlyConfigGovernor {
_freeze(_id);
}
/**
* @notice Enact a bulk list of ACL operations
*/
function bulk(BulkOp[] calldata _op, bytes32[] calldata _id, address[] calldata _who) external onlyConfigGovernor {
_bulk(_op, _id, _who);
}
/**
* @notice Set module `_id` to `_addr`
* @param _id ID of the module to be set
* @param _addr Address of the module to be set
*/
function setModule(bytes32 _id, address _addr) external onlyModulesGovernor {
_setModule(_id, _addr);
}
/**
* @notice Set and link many modules at once
* @param _newModuleIds List of IDs of the new modules to be set
* @param _newModuleAddresses List of addresses of the new modules to be set
* @param _newModuleLinks List of IDs of the modules that will be linked in the new modules being set
* @param _currentModulesToBeSynced List of addresses of current modules to be re-linked to the new modules being set
*/
function setModules(
bytes32[] calldata _newModuleIds,
address[] calldata _newModuleAddresses,
bytes32[] calldata _newModuleLinks,
address[] calldata _currentModulesToBeSynced
)
external
onlyModulesGovernor
{
// We only care about the modules being set, links are optional
require(_newModuleIds.length == _newModuleAddresses.length, ERROR_INVALID_IMPLS_INPUT_LENGTH);
// First set the addresses of the new modules or the modules to be updated
for (uint256 i = 0; i < _newModuleIds.length; i++) {
_setModule(_newModuleIds[i], _newModuleAddresses[i]);
}
// Then sync the links of the new modules based on the list of IDs specified (ideally the IDs of their dependencies)
_syncModuleLinks(_newModuleAddresses, _newModuleLinks);
// Finally sync the links of the existing modules to be synced to the new modules being set
_syncModuleLinks(_currentModulesToBeSynced, _newModuleIds);
}
/**
* @notice Sync modules for a list of modules IDs based on their current implementation address
* @param _modulesToBeSynced List of addresses of connected modules to be synced
* @param _idsToBeSet List of IDs of the modules included in the sync
*/
function syncModuleLinks(address[] calldata _modulesToBeSynced, bytes32[] calldata _idsToBeSet)
external
onlyModulesGovernor
{
require(_idsToBeSet.length > 0 && _modulesToBeSynced.length > 0, ERROR_INVALID_IMPLS_INPUT_LENGTH);
_syncModuleLinks(_modulesToBeSynced, _idsToBeSet);
}
/**
* @notice Disable module `_addr`
* @dev Current modules can be disabled to allow pausing the court. However, these can be enabled back again, see `enableModule`
* @param _addr Address of the module to be disabled
*/
function disableModule(address _addr) external onlyModulesGovernor {
Module storage module = allModules[_addr];
_ensureModuleExists(module);
require(!module.disabled, ERROR_MODULE_ALREADY_DISABLED);
module.disabled = true;
emit ModuleDisabled(module.id, _addr);
}
/**
* @notice Enable module `_addr`
* @param _addr Address of the module to be enabled
*/
function enableModule(address _addr) external onlyModulesGovernor {
Module storage module = allModules[_addr];
_ensureModuleExists(module);
require(module.disabled, ERROR_MODULE_ALREADY_ENABLED);
module.disabled = false;
emit ModuleEnabled(module.id, _addr);
}
/**
* @notice Set custom function `_sig` for `_target`
* @param _sig Signature of the function to be set
* @param _target Address of the target implementation to be registered for the given signature
*/
function setCustomFunction(bytes4 _sig, address _target) external onlyModulesGovernor {
customFunctions[_sig] = _target;
emit CustomFunctionSet(_sig, _target);
}
/**
* @dev Tell the full Court configuration parameters at a certain term
* @param _termId Identification number of the term querying the Court config of
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
*/
function getConfig(uint64 _termId) external view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
)
{
uint64 lastEnsuredTermId = _lastEnsuredTermId();
return _getConfigAt(_termId, lastEnsuredTermId);
}
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) {
uint64 lastEnsuredTermId = _lastEnsuredTermId();
return _getDraftConfig(_termId, lastEnsuredTermId);
}
/**
* @dev Tell the min active balance config at a certain term
* @param _termId Identification number of the term querying the min active balance config of
* @return Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getMinActiveBalance(uint64 _termId) external view returns (uint256) {
uint64 lastEnsuredTermId = _lastEnsuredTermId();
return _getMinActiveBalance(_termId, lastEnsuredTermId);
}
/**
* @dev Tell the address of the funds governor
* @return Address of the funds governor
*/
function getFundsGovernor() external view returns (address) {
return governor.funds;
}
/**
* @dev Tell the address of the config governor
* @return Address of the config governor
*/
function getConfigGovernor() external view returns (address) {
return governor.config;
}
/**
* @dev Tell the address of the modules governor
* @return Address of the modules governor
*/
function getModulesGovernor() external view returns (address) {
return governor.modules;
}
/**
* @dev Tell if a given module is active
* @param _id ID of the module to be checked
* @param _addr Address of the module to be checked
* @return True if the given module address has the requested ID and is enabled
*/
function isActive(bytes32 _id, address _addr) external view returns (bool) {
Module storage module = allModules[_addr];
return module.id == _id && !module.disabled;
}
/**
* @dev Tell the current ID and disable status of a module based on a given address
* @param _addr Address of the requested module
* @return id ID of the module being queried
* @return disabled Whether the module has been disabled
*/
function getModuleByAddress(address _addr) external view returns (bytes32 id, bool disabled) {
Module storage module = allModules[_addr];
id = module.id;
disabled = module.disabled;
}
/**
* @dev Tell the current address and disable status of a module based on a given ID
* @param _id ID of the module being queried
* @return addr Current address of the requested module
* @return disabled Whether the module has been disabled
*/
function getModule(bytes32 _id) external view returns (address addr, bool disabled) {
return _getModule(_id);
}
/**
* @dev Tell the information for the current DisputeManager module
* @return addr Current address of the DisputeManager module
* @return disabled Whether the module has been disabled
*/
function getDisputeManager() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_DISPUTE_MANAGER);
}
/**
* @dev Tell the information for the current GuardiansRegistry module
* @return addr Current address of the GuardiansRegistry module
* @return disabled Whether the module has been disabled
*/
function getGuardiansRegistry() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_GUARDIANS_REGISTRY);
}
/**
* @dev Tell the information for the current Voting module
* @return addr Current address of the Voting module
* @return disabled Whether the module has been disabled
*/
function getVoting() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_VOTING);
}
/**
* @dev Tell the information for the current PaymentsBook module
* @return addr Current address of the PaymentsBook module
* @return disabled Whether the module has been disabled
*/
function getPaymentsBook() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_PAYMENTS_BOOK);
}
/**
* @dev Tell the information for the current Treasury module
* @return addr Current address of the Treasury module
* @return disabled Whether the module has been disabled
*/
function getTreasury() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_TREASURY);
}
/**
* @dev Tell the target registered for a custom function
* @param _sig Signature of the function being queried
* @return Address of the target where the function call will be forwarded
*/
function getCustomFunction(bytes4 _sig) external view returns (address) {
return customFunctions[_sig];
}
/**
* @dev Internal function to set the address of the funds governor
* @param _newFundsGovernor Address of the new config governor to be set
*/
function _setFundsGovernor(address _newFundsGovernor) internal {
emit FundsGovernorChanged(governor.funds, _newFundsGovernor);
governor.funds = _newFundsGovernor;
}
/**
* @dev Internal function to set the address of the config governor
* @param _newConfigGovernor Address of the new config governor to be set
*/
function _setConfigGovernor(address _newConfigGovernor) internal {
emit ConfigGovernorChanged(governor.config, _newConfigGovernor);
governor.config = _newConfigGovernor;
}
/**
* @dev Internal function to set the address of the modules governor
* @param _newModulesGovernor Address of the new modules governor to be set
*/
function _setModulesGovernor(address _newModulesGovernor) internal {
emit ModulesGovernorChanged(governor.modules, _newModulesGovernor);
governor.modules = _newModulesGovernor;
}
/**
* @dev Internal function to set an address as the current implementation for a module
* Note that the disabled condition is not affected, if the module was not set before it will be enabled by default
* @param _id Id of the module to be set
* @param _addr Address of the module to be set
*/
function _setModule(bytes32 _id, address _addr) internal {
require(isContract(_addr), ERROR_IMPLEMENTATION_NOT_CONTRACT);
currentModules[_id] = _addr;
allModules[_addr].id = _id;
emit ModuleSet(_id, _addr);
}
/**
* @dev Internal function to sync the modules for a list of modules IDs based on their current implementation address
* @param _modulesToBeSynced List of addresses of connected modules to be synced
* @param _idsToBeSet List of IDs of the modules to be linked
*/
function _syncModuleLinks(address[] memory _modulesToBeSynced, bytes32[] memory _idsToBeSet) internal {
address[] memory addressesToBeSet = new address[](_idsToBeSet.length);
// Load the addresses associated with the requested module ids
for (uint256 i = 0; i < _idsToBeSet.length; i++) {
address moduleAddress = _getModuleAddress(_idsToBeSet[i]);
Module storage module = allModules[moduleAddress];
_ensureModuleExists(module);
addressesToBeSet[i] = moduleAddress;
}
// Update the links of all the requested modules
for (uint256 j = 0; j < _modulesToBeSynced.length; j++) {
IModulesLinker(_modulesToBeSynced[j]).linkModules(_idsToBeSet, addressesToBeSet);
}
}
/**
* @dev Internal function to notify when a term has been transitioned
* @param _termId Identification number of the new current term that has been transitioned
*/
function _onTermTransitioned(uint64 _termId) internal {
_ensureTermConfig(_termId);
}
/**
* @dev Internal function to check if a module was set
* @param _module Module to be checked
*/
function _ensureModuleExists(Module storage _module) internal view {
require(_module.id != bytes32(0), ERROR_MODULE_NOT_SET);
}
/**
* @dev Internal function to tell the information for a module based on a given ID
* @param _id ID of the module being queried
* @return addr Current address of the requested module
* @return disabled Whether the module has been disabled
*/
function _getModule(bytes32 _id) internal view returns (address addr, bool disabled) {
addr = _getModuleAddress(_id);
disabled = _isModuleDisabled(addr);
}
/**
* @dev Tell the current address for a module by ID
* @param _id ID of the module being queried
* @return Current address of the requested module
*/
function _getModuleAddress(bytes32 _id) internal view returns (address) {
return currentModules[_id];
}
/**
* @dev Tell whether a module is disabled
* @param _addr Address of the module being queried
* @return True if the module is disabled, false otherwise
*/
function _isModuleDisabled(address _addr) internal view returns (bool) {
return allModules[_addr].disabled;
}
}
contract ConfigConsumer is CourtConfigData {
/**
* @dev Internal function to fetch the address of the Config module from the controller
* @return Address of the Config module
*/
function _courtConfig() internal view returns (IConfig);
/**
* @dev Internal function to get the Court config for a certain term
* @param _termId Identification number of the term querying the Court config of
* @return Court config for the given term
*/
function _getConfigAt(uint64 _termId) internal view returns (Config memory) {
(IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance) = _courtConfig().getConfig(_termId);
Config memory config;
config.fees = FeesConfig({
token: _feeToken,
guardianFee: _fees[0],
draftFee: _fees[1],
settleFee: _fees[2],
finalRoundReduction: _pcts[1]
});
config.disputes = DisputesConfig({
evidenceTerms: _roundStateDurations[0],
commitTerms: _roundStateDurations[1],
revealTerms: _roundStateDurations[2],
appealTerms: _roundStateDurations[3],
appealConfirmTerms: _roundStateDurations[4],
penaltyPct: _pcts[0],
firstRoundGuardiansNumber: _roundParams[0],
appealStepFactor: _roundParams[1],
maxRegularAppealRounds: _roundParams[2],
finalRoundLockTerms: _roundParams[3],
appealCollateralFactor: _appealCollateralParams[0],
appealConfirmCollateralFactor: _appealCollateralParams[1]
});
config.minActiveBalance = _minActiveBalance;
return config;
}
/**
* @dev Internal function to get the draft config for a given term
* @param _termId Identification number of the term querying the draft config of
* @return Draft config for the given term
*/
function _getDraftConfig(uint64 _termId) internal view returns (DraftConfig memory) {
(IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) = _courtConfig().getDraftConfig(_termId);
return DraftConfig({ feeToken: feeToken, draftFee: draftFee, penaltyPct: penaltyPct });
}
/**
* @dev Internal function to get the min active balance config for a given term
* @param _termId Identification number of the term querying the min active balance config of
* @return Minimum amount of guardian tokens that can be activated
*/
function _getMinActiveBalance(uint64 _termId) internal view returns (uint256) {
return _courtConfig().getMinActiveBalance(_termId);
}
}
/*
* SPDX-License-Identifier: MIT
*/
interface ICRVotingOwner {
/**
* @dev Ensure votes can be committed for a vote instance, revert otherwise
* @param _voteId ID of the vote instance to request the weight of a voter for
*/
function ensureCanCommit(uint256 _voteId) external;
/**
* @dev Ensure a certain voter can commit votes for a vote instance, revert otherwise
* @param _voteId ID of the vote instance to request the weight of a voter for
* @param _voter Address of the voter querying the weight of
*/
function ensureCanCommit(uint256 _voteId, address _voter) external;
/**
* @dev Ensure a certain voter can reveal votes for vote instance, revert otherwise
* @param _voteId ID of the vote instance to request the weight of a voter for
* @param _voter Address of the voter querying the weight of
* @return Weight of the requested guardian for the requested vote instance
*/
function ensureCanReveal(uint256 _voteId, address _voter) external returns (uint64);
}
/*
* SPDX-License-Identifier: MIT
*/
interface ICRVoting {
/**
* @dev Create a new vote instance
* @dev This function can only be called by the CRVoting owner
* @param _voteId ID of the new vote instance to be created
* @param _possibleOutcomes Number of possible outcomes for the new vote instance to be created
*/
function createVote(uint256 _voteId, uint8 _possibleOutcomes) external;
/**
* @dev Get the winning outcome of a vote instance
* @param _voteId ID of the vote instance querying the winning outcome of
* @return Winning outcome of the given vote instance or refused in case it's missing
*/
function getWinningOutcome(uint256 _voteId) external view returns (uint8);
/**
* @dev Get the tally of an outcome for a certain vote instance
* @param _voteId ID of the vote instance querying the tally of
* @param _outcome Outcome querying the tally of
* @return Tally of the outcome being queried for the given vote instance
*/
function getOutcomeTally(uint256 _voteId, uint8 _outcome) external view returns (uint256);
/**
* @dev Tell whether an outcome is valid for a given vote instance or not
* @param _voteId ID of the vote instance to check the outcome of
* @param _outcome Outcome to check if valid or not
* @return True if the given outcome is valid for the requested vote instance, false otherwise
*/
function isValidOutcome(uint256 _voteId, uint8 _outcome) external view returns (bool);
/**
* @dev Get the outcome voted by a voter for a certain vote instance
* @param _voteId ID of the vote instance querying the outcome of
* @param _voter Address of the voter querying the outcome of
* @return Outcome of the voter for the given vote instance
*/
function getVoterOutcome(uint256 _voteId, address _voter) external view returns (uint8);
/**
* @dev Tell whether a voter voted in favor of a certain outcome in a vote instance or not
* @param _voteId ID of the vote instance to query if a voter voted in favor of a certain outcome
* @param _outcome Outcome to query if the given voter voted in favor of
* @param _voter Address of the voter to query if voted in favor of the given outcome
* @return True if the given voter voted in favor of the given outcome, false otherwise
*/
function hasVotedInFavorOf(uint256 _voteId, uint8 _outcome, address _voter) external view returns (bool);
/**
* @dev Filter a list of voters based on whether they voted in favor of a certain outcome in a vote instance or not
* @param _voteId ID of the vote instance to be checked
* @param _outcome Outcome to filter the list of voters of
* @param _voters List of addresses of the voters to be filtered
* @return List of results to tell whether a voter voted in favor of the given outcome or not
*/
function getVotersInFavorOf(uint256 _voteId, uint8 _outcome, address[] calldata _voters) external view returns (bool[] memory);
}
/*
* SPDX-License-Identifier: MIT
*/
interface ITreasury {
/**
* @dev Assign a certain amount of tokens to an account
* @param _token ERC20 token to be assigned
* @param _to Address of the recipient that will be assigned the tokens to
* @param _amount Amount of tokens to be assigned to the recipient
*/
function assign(IERC20 _token, address _to, uint256 _amount) external;
/**
* @dev Withdraw a certain amount of tokens
* @param _token ERC20 token to be withdrawn
* @param _from Address withdrawing the tokens from
* @param _to Address of the recipient that will receive the tokens
* @param _amount Amount of tokens to be withdrawn from the sender
*/
function withdraw(IERC20 _token, address _from, address _to, uint256 _amount) external;
}
/*
* SPDX-License-Identifier: MIT
*/
interface IPaymentsBook {
/**
* @dev Pay an amount of tokens
* @param _token Address of the token being paid
* @param _amount Amount of tokens being paid
* @param _payer Address paying on behalf of
* @param _data Optional data
*/
function pay(address _token, uint256 _amount, address _payer, bytes calldata _data) external payable;
}
contract Controlled is IModulesLinker, IsContract, ModuleIds, ConfigConsumer {
string private constant ERROR_MODULE_NOT_SET = "CTD_MODULE_NOT_SET";
string private constant ERROR_INVALID_MODULES_LINK_INPUT = "CTD_INVALID_MODULES_LINK_INPUT";
string private constant ERROR_CONTROLLER_NOT_CONTRACT = "CTD_CONTROLLER_NOT_CONTRACT";
string private constant ERROR_SENDER_NOT_ALLOWED = "CTD_SENDER_NOT_ALLOWED";
string private constant ERROR_SENDER_NOT_CONTROLLER = "CTD_SENDER_NOT_CONTROLLER";
string private constant ERROR_SENDER_NOT_CONFIG_GOVERNOR = "CTD_SENDER_NOT_CONFIG_GOVERNOR";
string private constant ERROR_SENDER_NOT_ACTIVE_VOTING = "CTD_SENDER_NOT_ACTIVE_VOTING";
string private constant ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER = "CTD_SEND_NOT_ACTIVE_DISPUTE_MGR";
string private constant ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER = "CTD_SEND_NOT_CURRENT_DISPUTE_MGR";
// Address of the controller
Controller public controller;
// List of modules linked indexed by ID
mapping (bytes32 => address) public linkedModules;
event ModuleLinked(bytes32 id, address addr);
/**
* @dev Ensure the msg.sender is the controller's config governor
*/
modifier onlyConfigGovernor {
require(msg.sender == _configGovernor(), ERROR_SENDER_NOT_CONFIG_GOVERNOR);
_;
}
/**
* @dev Ensure the msg.sender is the controller
*/
modifier onlyController() {
require(msg.sender == address(controller), ERROR_SENDER_NOT_CONTROLLER);
_;
}
/**
* @dev Ensure the msg.sender is an active DisputeManager module
*/
modifier onlyActiveDisputeManager() {
require(controller.isActive(MODULE_ID_DISPUTE_MANAGER, msg.sender), ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER);
_;
}
/**
* @dev Ensure the msg.sender is the current DisputeManager module
*/
modifier onlyCurrentDisputeManager() {
(address addr, bool disabled) = controller.getDisputeManager();
require(msg.sender == addr, ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER);
require(!disabled, ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER);
_;
}
/**
* @dev Ensure the msg.sender is an active Voting module
*/
modifier onlyActiveVoting() {
require(controller.isActive(MODULE_ID_VOTING, msg.sender), ERROR_SENDER_NOT_ACTIVE_VOTING);
_;
}
/**
* @dev This modifier will check that the sender is the user to act on behalf of or someone with the required permission
* @param _user Address of the user to act on behalf of
*/
modifier authenticateSender(address _user) {
_authenticateSender(_user);
_;
}
/**
* @dev Constructor function
* @param _controller Address of the controller
*/
constructor(Controller _controller) public {
require(isContract(address(_controller)), ERROR_CONTROLLER_NOT_CONTRACT);
controller = _controller;
}
/**
* @notice Update the implementation links of a list of modules
* @dev The controller is expected to ensure the given addresses are correct modules
* @param _ids List of IDs of the modules to be updated
* @param _addresses List of module addresses to be updated
*/
function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external onlyController {
require(_ids.length == _addresses.length, ERROR_INVALID_MODULES_LINK_INPUT);
for (uint256 i = 0; i < _ids.length; i++) {
linkedModules[_ids[i]] = _addresses[i];
emit ModuleLinked(_ids[i], _addresses[i]);
}
}
/**
* @dev Internal function to ensure the Court term is up-to-date, it will try to update it if not
* @return Identification number of the current Court term
*/
function _ensureCurrentTerm() internal returns (uint64) {
return _clock().ensureCurrentTerm();
}
/**
* @dev Internal function to fetch the last ensured term ID of the Court
* @return Identification number of the last ensured term
*/
function _getLastEnsuredTermId() internal view returns (uint64) {
return _clock().getLastEnsuredTermId();
}
/**
* @dev Internal function to tell the current term identification number
* @return Identification number of the current term
*/
function _getCurrentTermId() internal view returns (uint64) {
return _clock().getCurrentTermId();
}
/**
* @dev Internal function to fetch the controller's config governor
* @return Address of the controller's config governor
*/
function _configGovernor() internal view returns (address) {
return controller.getConfigGovernor();
}
/**
* @dev Internal function to fetch the address of the DisputeManager module
* @return Address of the DisputeManager module
*/
function _disputeManager() internal view returns (IDisputeManager) {
return IDisputeManager(_getLinkedModule(MODULE_ID_DISPUTE_MANAGER));
}
/**
* @dev Internal function to fetch the address of the GuardianRegistry module implementation
* @return Address of the GuardianRegistry module implementation
*/
function _guardiansRegistry() internal view returns (IGuardiansRegistry) {
return IGuardiansRegistry(_getLinkedModule(MODULE_ID_GUARDIANS_REGISTRY));
}
/**
* @dev Internal function to fetch the address of the Voting module implementation
* @return Address of the Voting module implementation
*/
function _voting() internal view returns (ICRVoting) {
return ICRVoting(_getLinkedModule(MODULE_ID_VOTING));
}
/**
* @dev Internal function to fetch the address of the PaymentsBook module implementation
* @return Address of the PaymentsBook module implementation
*/
function _paymentsBook() internal view returns (IPaymentsBook) {
return IPaymentsBook(_getLinkedModule(MODULE_ID_PAYMENTS_BOOK));
}
/**
* @dev Internal function to fetch the address of the Treasury module implementation
* @return Address of the Treasury module implementation
*/
function _treasury() internal view returns (ITreasury) {
return ITreasury(_getLinkedModule(MODULE_ID_TREASURY));
}
/**
* @dev Internal function to tell the address linked for a module based on a given ID
* @param _id ID of the module being queried
* @return Linked address of the requested module
*/
function _getLinkedModule(bytes32 _id) internal view returns (address) {
address module = linkedModules[_id];
require(module != address(0), ERROR_MODULE_NOT_SET);
return module;
}
/**
* @dev Internal function to fetch the address of the Clock module from the controller
* @return Address of the Clock module
*/
function _clock() internal view returns (IClock) {
return IClock(controller);
}
/**
* @dev Internal function to fetch the address of the Config module from the controller
* @return Address of the Config module
*/
function _courtConfig() internal view returns (IConfig) {
return IConfig(controller);
}
/**
* @dev Ensure that the sender is the user to act on behalf of or someone with the required permission
* @param _user Address of the user to act on behalf of
*/
function _authenticateSender(address _user) internal view {
require(_isSenderAllowed(_user), ERROR_SENDER_NOT_ALLOWED);
}
/**
* @dev Tell whether the sender is the user to act on behalf of or someone with the required permission
* @param _user Address of the user to act on behalf of
* @return True if the sender is the user to act on behalf of or someone with the required permission, false otherwise
*/
function _isSenderAllowed(address _user) internal view returns (bool) {
return msg.sender == _user || _hasRole(msg.sender);
}
/**
* @dev Tell whether an address holds the required permission to access the requested functionality
* @param _addr Address being checked
* @return True if the given address has the required permission to access the requested functionality, false otherwise
*/
function _hasRole(address _addr) internal view returns (bool) {
bytes32 roleId = keccak256(abi.encodePacked(address(this), msg.sig));
return controller.hasRole(_addr, roleId);
}
}
contract ControlledRecoverable is Controlled {
using SafeERC20 for IERC20;
string private constant ERROR_SENDER_NOT_FUNDS_GOVERNOR = "CTD_SENDER_NOT_FUNDS_GOVERNOR";
string private constant ERROR_INSUFFICIENT_RECOVER_FUNDS = "CTD_INSUFFICIENT_RECOVER_FUNDS";
string private constant ERROR_RECOVER_TOKEN_FUNDS_FAILED = "CTD_RECOVER_TOKEN_FUNDS_FAILED";
event RecoverFunds(address token, address recipient, uint256 balance);
/**
* @dev Ensure the msg.sender is the controller's funds governor
*/
modifier onlyFundsGovernor {
require(msg.sender == controller.getFundsGovernor(), ERROR_SENDER_NOT_FUNDS_GOVERNOR);
_;
}
/**
* @notice Transfer all `_token` tokens to `_to`
* @param _token Address of the token to be recovered
* @param _to Address of the recipient that will be receive all the funds of the requested token
*/
function recoverFunds(address _token, address payable _to) external payable onlyFundsGovernor {
uint256 balance;
if (_token == address(0)) {
balance = address(this).balance;
require(_to.send(balance), ERROR_RECOVER_TOKEN_FUNDS_FAILED);
} else {
balance = IERC20(_token).balanceOf(address(this));
require(balance > 0, ERROR_INSUFFICIENT_RECOVER_FUNDS);
// No need to verify _token to be a contract as we have already checked the balance
require(IERC20(_token).safeTransfer(_to, balance), ERROR_RECOVER_TOKEN_FUNDS_FAILED);
}
emit RecoverFunds(_token, _to, balance);
}
}
contract GuardiansRegistry is IGuardiansRegistry, ControlledRecoverable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using PctHelpers for uint256;
using HexSumTree for HexSumTree.Tree;
using GuardiansTreeSortition for HexSumTree.Tree;
string private constant ERROR_NOT_CONTRACT = "GR_NOT_CONTRACT";
string private constant ERROR_INVALID_ZERO_AMOUNT = "GR_INVALID_ZERO_AMOUNT";
string private constant ERROR_INVALID_ACTIVATION_AMOUNT = "GR_INVALID_ACTIVATION_AMOUNT";
string private constant ERROR_INVALID_DEACTIVATION_AMOUNT = "GR_INVALID_DEACTIVATION_AMOUNT";
string private constant ERROR_INVALID_LOCKED_AMOUNTS_LENGTH = "GR_INVALID_LOCKED_AMOUNTS_LEN";
string private constant ERROR_INVALID_REWARDED_GUARDIANS_LENGTH = "GR_INVALID_REWARD_GUARDIANS_LEN";
string private constant ERROR_ACTIVE_BALANCE_BELOW_MIN = "GR_ACTIVE_BALANCE_BELOW_MIN";
string private constant ERROR_NOT_ENOUGH_AVAILABLE_BALANCE = "GR_NOT_ENOUGH_AVAILABLE_BALANCE";
string private constant ERROR_CANNOT_REDUCE_DEACTIVATION_REQUEST = "GR_CANT_REDUCE_DEACTIVATION_REQ";
string private constant ERROR_TOKEN_TRANSFER_FAILED = "GR_TOKEN_TRANSFER_FAILED";
string private constant ERROR_TOKEN_APPROVE_NOT_ALLOWED = "GR_TOKEN_APPROVE_NOT_ALLOWED";
string private constant ERROR_BAD_TOTAL_ACTIVE_BALANCE_LIMIT = "GR_BAD_TOTAL_ACTIVE_BAL_LIMIT";
string private constant ERROR_TOTAL_ACTIVE_BALANCE_EXCEEDED = "GR_TOTAL_ACTIVE_BALANCE_EXCEEDED";
string private constant ERROR_DEACTIVATION_AMOUNT_EXCEEDS_LOCK = "GR_DEACTIV_AMOUNT_EXCEEDS_LOCK";
string private constant ERROR_CANNOT_UNLOCK_ACTIVATION = "GR_CANNOT_UNLOCK_ACTIVATION";
string private constant ERROR_ZERO_LOCK_ACTIVATION = "GR_ZERO_LOCK_ACTIVATION";
string private constant ERROR_INVALID_UNLOCK_ACTIVATION_AMOUNT = "GR_INVALID_UNLOCK_ACTIVAT_AMOUNT";
string private constant ERROR_LOCK_MANAGER_NOT_ALLOWED = "GR_LOCK_MANAGER_NOT_ALLOWED";
string private constant ERROR_WITHDRAWALS_LOCK = "GR_WITHDRAWALS_LOCK";
// Address that will be used to burn guardian tokens
address internal constant BURN_ACCOUNT = address(0x000000000000000000000000000000000000dEaD);
// Maximum number of sortition iterations allowed per draft call
uint256 internal constant MAX_DRAFT_ITERATIONS = 10;
// "ERC20-lite" interface to provide help for tooling
string public constant name = "Court Staked Aragon Network Token";
string public constant symbol = "sANT";
uint8 public constant decimals = 18;
/**
* @dev Guardians have three kind of balances, these are:
* - active: tokens activated for the Court that can be locked in case the guardian is drafted
* - locked: amount of active tokens that are locked for a draft
* - available: tokens that are not activated for the Court and can be withdrawn by the guardian at any time
*
* Due to a gas optimization for drafting, the "active" tokens are stored in a `HexSumTree`, while the others
* are stored in this contract as `lockedBalance` and `availableBalance` respectively. Given that the guardians'
* active balances cannot be affected during the current Court term, if guardians want to deactivate some of
* their active tokens, their balance will be updated for the following term, and they won't be allowed to
* withdraw them until the current term has ended.
*
* Note that even though guardians balances are stored separately, all the balances are held by this contract.
*/
struct Guardian {
uint256 id; // Key in the guardians tree used for drafting
uint256 lockedBalance; // Maximum amount of tokens that can be slashed based on the guardian's drafts
uint256 availableBalance; // Available tokens that can be withdrawn at any time
uint64 withdrawalsLockTermId; // Term ID until which the guardian's withdrawals will be locked
ActivationLocks activationLocks; // Guardian's activation locks
DeactivationRequest deactivationRequest; // Guardian's pending deactivation request
}
/**
* @dev Guardians can define lock managers to control their minimum active balance in the registry
*/
struct ActivationLocks {
uint256 total; // Total amount of active balance locked
mapping (address => uint256) lockedBy; // List of locked amounts indexed by lock manager
}
/**
* @dev Given that the guardians balances cannot be affected during a Court term, if guardians want to deactivate some
* of their tokens, the tree will always be updated for the following term, and they won't be able to
* withdraw the requested amount until the current term has finished. Thus, we need to keep track the term
* when a token deactivation was requested and its corresponding amount.
*/
struct DeactivationRequest {
uint256 amount; // Amount requested for deactivation
uint64 availableTermId; // Term ID when guardians can withdraw their requested deactivation tokens
}
/**
* @dev Internal struct to wrap all the params required to perform guardians drafting
*/
struct DraftParams {
bytes32 termRandomness; // Randomness seed to be used for the draft
uint256 disputeId; // ID of the dispute being drafted
uint64 termId; // Term ID of the dispute's draft term
uint256 selectedGuardians; // Number of guardians already selected for the draft
uint256 batchRequestedGuardians; // Number of guardians to be selected in the given batch of the draft
uint256 roundRequestedGuardians; // Total number of guardians requested to be drafted
uint256 draftLockAmount; // Amount of tokens to be locked to each drafted guardian
uint256 iteration; // Sortition iteration number
}
// Maximum amount of total active balance that can be held in the registry
uint256 public totalActiveBalanceLimit;
// Guardian ERC20 token
IERC20 public guardiansToken;
// Mapping of guardian data indexed by address
mapping (address => Guardian) internal guardiansByAddress;
// Mapping of guardian addresses indexed by id
mapping (uint256 => address) internal guardiansAddressById;
// Tree to store guardians active balance by term for the drafting process
HexSumTree.Tree internal tree;
event Staked(address indexed guardian, uint256 amount, uint256 total);
event Unstaked(address indexed guardian, uint256 amount, uint256 total);
event GuardianActivated(address indexed guardian, uint64 fromTermId, uint256 amount);
event GuardianDeactivationRequested(address indexed guardian, uint64 availableTermId, uint256 amount);
event GuardianDeactivationProcessed(address indexed guardian, uint64 availableTermId, uint256 amount, uint64 processedTermId);
event GuardianDeactivationUpdated(address indexed guardian, uint64 availableTermId, uint256 amount, uint64 updateTermId);
event GuardianActivationLockChanged(address indexed guardian, address indexed lockManager, uint256 amount, uint256 total);
event GuardianBalanceLocked(address indexed guardian, uint256 amount);
event GuardianBalanceUnlocked(address indexed guardian, uint256 amount);
event GuardianSlashed(address indexed guardian, uint256 amount, uint64 effectiveTermId);
event GuardianTokensAssigned(address indexed guardian, uint256 amount);
event GuardianTokensBurned(uint256 amount);
event GuardianTokensCollected(address indexed guardian, uint256 amount, uint64 effectiveTermId);
event TotalActiveBalanceLimitChanged(uint256 previousTotalActiveBalanceLimit, uint256 currentTotalActiveBalanceLimit);
/**
* @dev Constructor function
* @param _controller Address of the controller
* @param _guardiansToken Address of the ERC20 token to be used as guardian token for the registry
* @param _totalActiveBalanceLimit Maximum amount of total active balance that can be held in the registry
*/
constructor(Controller _controller, IERC20 _guardiansToken, uint256 _totalActiveBalanceLimit) Controlled(_controller) public {
require(isContract(address(_guardiansToken)), ERROR_NOT_CONTRACT);
guardiansToken = _guardiansToken;
_setTotalActiveBalanceLimit(_totalActiveBalanceLimit);
tree.init();
// First tree item is an empty guardian
assert(tree.insert(0, 0) == 0);
}
/**
* @notice Stake `@tokenAmount(self.token(), _amount)` for `_guardian`
* @param _guardian Address of the guardian to stake tokens to
* @param _amount Amount of tokens to be staked
*/
function stake(address _guardian, uint256 _amount) external {
_stake(_guardian, _amount);
}
/**
* @notice Unstake `@tokenAmount(self.token(), _amount)` from `_guardian`
* @param _guardian Address of the guardian to unstake tokens from
* @param _amount Amount of tokens to be unstaked
*/
function unstake(address _guardian, uint256 _amount) external authenticateSender(_guardian) {
_unstake(_guardian, _amount);
}
/**
* @notice Activate `@tokenAmount(self.token(), _amount)` for `_guardian`
* @param _guardian Address of the guardian activating the tokens for
* @param _amount Amount of guardian tokens to be activated for the next term
*/
function activate(address _guardian, uint256 _amount) external authenticateSender(_guardian) {
_activate(_guardian, _amount);
}
/**
* @notice Deactivate `_amount == 0 ? 'all unlocked tokens' : @tokenAmount(self.token(), _amount)` for `_guardian`
* @param _guardian Address of the guardian deactivating the tokens for
* @param _amount Amount of guardian tokens to be deactivated for the next term
*/
function deactivate(address _guardian, uint256 _amount) external authenticateSender(_guardian) {
_deactivate(_guardian, _amount);
}
/**
* @notice Stake and activate `@tokenAmount(self.token(), _amount)` for `_guardian`
* @param _guardian Address of the guardian staking and activating tokens for
* @param _amount Amount of tokens to be staked and activated
*/
function stakeAndActivate(address _guardian, uint256 _amount) external authenticateSender(_guardian) {
_stake(_guardian, _amount);
_activate(_guardian, _amount);
}
/**
* @notice Lock `@tokenAmount(self.token(), _amount)` of `_guardian`'s active balance
* @param _guardian Address of the guardian locking the activation for
* @param _lockManager Address of the lock manager that will control the lock
* @param _amount Amount of active tokens to be locked
*/
function lockActivation(address _guardian, address _lockManager, uint256 _amount) external {
// Make sure the sender is the guardian, someone allowed by the guardian, or the lock manager itself
bool isLockManagerAllowed = msg.sender == _lockManager || _isSenderAllowed(_guardian);
// Make sure that the given lock manager is allowed
require(isLockManagerAllowed && _hasRole(_lockManager), ERROR_LOCK_MANAGER_NOT_ALLOWED);
_lockActivation(_guardian, _lockManager, _amount);
}
/**
* @notice Unlock `_amount == 0 ? 'all unlocked tokens' : @tokenAmount(self.token(), _amount)` of `_guardian`'s active balance
* @param _guardian Address of the guardian unlocking the active balance of
* @param _lockManager Address of the lock manager controlling the lock
* @param _amount Amount of active tokens to be unlocked
* @param _requestDeactivation Whether the unlocked amount must be requested for deactivation immediately
*/
function unlockActivation(address _guardian, address _lockManager, uint256 _amount, bool _requestDeactivation) external {
ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks;
uint256 lockedAmount = activationLocks.lockedBy[_lockManager];
require(lockedAmount > 0, ERROR_ZERO_LOCK_ACTIVATION);
uint256 amountToUnlock = _amount == 0 ? lockedAmount : _amount;
require(amountToUnlock <= lockedAmount, ERROR_INVALID_UNLOCK_ACTIVATION_AMOUNT);
// Always allow the lock manager to unlock
bool canUnlock = _lockManager == msg.sender || ILockManager(_lockManager).canUnlock(_guardian, amountToUnlock);
require(canUnlock, ERROR_CANNOT_UNLOCK_ACTIVATION);
uint256 newLockedAmount = lockedAmount.sub(amountToUnlock);
uint256 newTotalLocked = activationLocks.total.sub(amountToUnlock);
activationLocks.total = newTotalLocked;
activationLocks.lockedBy[_lockManager] = newLockedAmount;
emit GuardianActivationLockChanged(_guardian, _lockManager, newLockedAmount, newTotalLocked);
// In order to request a deactivation, the request must have been originally authorized from the guardian or someone authorized to do it
if (_requestDeactivation) {
_authenticateSender(_guardian);
_deactivate(_guardian, _amount);
}
}
/**
* @notice Process a token deactivation requested for `_guardian` if there is any
* @param _guardian Address of the guardian to process the deactivation request of
*/
function processDeactivationRequest(address _guardian) external {
uint64 termId = _ensureCurrentTerm();
_processDeactivationRequest(_guardian, termId);
}
/**
* @notice Assign `@tokenAmount(self.token(), _amount)` to the available balance of `_guardian`
* @param _guardian Guardian to add an amount of tokens to
* @param _amount Amount of tokens to be added to the available balance of a guardian
*/
function assignTokens(address _guardian, uint256 _amount) external onlyActiveDisputeManager {
if (_amount > 0) {
_updateAvailableBalanceOf(_guardian, _amount, true);
emit GuardianTokensAssigned(_guardian, _amount);
}
}
/**
* @notice Burn `@tokenAmount(self.token(), _amount)`
* @param _amount Amount of tokens to be burned
*/
function burnTokens(uint256 _amount) external onlyActiveDisputeManager {
if (_amount > 0) {
_updateAvailableBalanceOf(BURN_ACCOUNT, _amount, true);
emit GuardianTokensBurned(_amount);
}
}
/**
* @notice Draft a set of guardians based on given requirements for a term id
* @param _params Array containing draft requirements:
* 0. bytes32 Term randomness
* 1. uint256 Dispute id
* 2. uint64 Current term id
* 3. uint256 Number of seats already filled
* 4. uint256 Number of seats left to be filled
* 5. uint64 Number of guardians required for the draft
* 6. uint16 Permyriad of the minimum active balance to be locked for the draft
*
* @return guardians List of guardians selected for the draft
* @return length Size of the list of the draft result
*/
function draft(uint256[7] calldata _params) external onlyActiveDisputeManager returns (address[] memory guardians, uint256 length) {
DraftParams memory draftParams = _buildDraftParams(_params);
guardians = new address[](draftParams.batchRequestedGuardians);
// Guardians returned by the tree multi-sortition may not have enough unlocked active balance to be drafted. Thus,
// we compute several sortitions until all the requested guardians are selected. To guarantee a different set of
// guardians on each sortition, the iteration number will be part of the random seed to be used in the sortition.
// Note that we are capping the number of iterations to avoid an OOG error, which means that this function could
// return less guardians than the requested number.
for (draftParams.iteration = 0;
length < draftParams.batchRequestedGuardians && draftParams.iteration < MAX_DRAFT_ITERATIONS;
draftParams.iteration++
) {
(uint256[] memory guardianIds, uint256[] memory activeBalances) = _treeSearch(draftParams);
for (uint256 i = 0; i < guardianIds.length && length < draftParams.batchRequestedGuardians; i++) {
// We assume the selected guardians are registered in the registry, we are not checking their addresses exist
address guardianAddress = guardiansAddressById[guardianIds[i]];
Guardian storage guardian = guardiansByAddress[guardianAddress];
// Compute new locked balance for a guardian based on the penalty applied when being drafted
uint256 newLockedBalance = guardian.lockedBalance.add(draftParams.draftLockAmount);
// Check if there is any deactivation requests for the next term. Drafts are always computed for the current term
// but we have to make sure we are locking an amount that will exist in the next term.
uint256 nextTermDeactivationRequestAmount = _deactivationRequestedAmountForTerm(guardian, draftParams.termId + 1);
// Check if guardian has enough active tokens to lock the requested amount for the draft, skip it otherwise.
uint256 currentActiveBalance = activeBalances[i];
if (currentActiveBalance >= newLockedBalance) {
// Check if the amount of active tokens for the next term is enough to lock the required amount for
// the draft. Otherwise, reduce the requested deactivation amount of the next term.
// Next term deactivation amount should always be less than current active balance, but we make sure using SafeMath
uint256 nextTermActiveBalance = currentActiveBalance.sub(nextTermDeactivationRequestAmount);
if (nextTermActiveBalance < newLockedBalance) {
// No need for SafeMath: we already checked values above
_reduceDeactivationRequest(guardianAddress, newLockedBalance - nextTermActiveBalance, draftParams.termId);
}
// Update the current active locked balance of the guardian
guardian.lockedBalance = newLockedBalance;
guardians[length++] = guardianAddress;
emit GuardianBalanceLocked(guardianAddress, draftParams.draftLockAmount);
}
}
}
}
/**
* @notice Slash a set of guardians based on their votes compared to the winning ruling. This function will unlock the
* corresponding locked balances of those guardians that are set to be slashed.
* @param _termId Current term id
* @param _guardians List of guardian addresses to be slashed
* @param _lockedAmounts List of amounts locked for each corresponding guardian that will be either slashed or returned
* @param _rewardedGuardians List of booleans to tell whether a guardian's active balance has to be slashed or not
* @return Total amount of slashed tokens
*/
function slashOrUnlock(uint64 _termId, address[] calldata _guardians, uint256[] calldata _lockedAmounts, bool[] calldata _rewardedGuardians)
external
onlyActiveDisputeManager
returns (uint256)
{
require(_guardians.length == _lockedAmounts.length, ERROR_INVALID_LOCKED_AMOUNTS_LENGTH);
require(_guardians.length == _rewardedGuardians.length, ERROR_INVALID_REWARDED_GUARDIANS_LENGTH);
uint64 nextTermId = _termId + 1;
uint256 collectedTokens;
for (uint256 i = 0; i < _guardians.length; i++) {
uint256 lockedAmount = _lockedAmounts[i];
address guardianAddress = _guardians[i];
Guardian storage guardian = guardiansByAddress[guardianAddress];
guardian.lockedBalance = guardian.lockedBalance.sub(lockedAmount);
// Slash guardian if requested. Note that there's no need to check if there was a deactivation
// request since we're working with already locked balances.
if (_rewardedGuardians[i]) {
emit GuardianBalanceUnlocked(guardianAddress, lockedAmount);
} else {
collectedTokens = collectedTokens.add(lockedAmount);
tree.update(guardian.id, nextTermId, lockedAmount, false);
emit GuardianSlashed(guardianAddress, lockedAmount, nextTermId);
}
}
return collectedTokens;
}
/**
* @notice Try to collect `@tokenAmount(self.token(), _amount)` from `_guardian` for the term #`_termId + 1`.
* @dev This function tries to decrease the active balance of a guardian for the next term based on the requested
* amount. It can be seen as a way to early-slash a guardian's active balance.
* @param _guardian Guardian to collect the tokens from
* @param _amount Amount of tokens to be collected from the given guardian and for the requested term id
* @param _termId Current term id
* @return True if the guardian has enough unlocked tokens to be collected for the requested term, false otherwise
*/
function collectTokens(address _guardian, uint256 _amount, uint64 _termId) external onlyActiveDisputeManager returns (bool) {
if (_amount == 0) {
return true;
}
uint64 nextTermId = _termId + 1;
Guardian storage guardian = guardiansByAddress[_guardian];
uint256 unlockedActiveBalance = _lastUnlockedActiveBalanceOf(guardian);
uint256 nextTermDeactivationRequestAmount = _deactivationRequestedAmountForTerm(guardian, nextTermId);
// Check if the guardian has enough unlocked tokens to collect the requested amount
// Note that we're also considering the deactivation request if there is any
uint256 totalUnlockedActiveBalance = unlockedActiveBalance.add(nextTermDeactivationRequestAmount);
if (_amount > totalUnlockedActiveBalance) {
return false;
}
// Check if the amount of active tokens is enough to collect the requested amount, otherwise reduce the requested deactivation amount of
// the next term. Note that this behaviour is different to the one when drafting guardians since this function is called as a side effect
// of a guardian deliberately voting in a final round, while drafts occur randomly.
if (_amount > unlockedActiveBalance) {
// No need for SafeMath: amounts were already checked above
uint256 amountToReduce = _amount - unlockedActiveBalance;
_reduceDeactivationRequest(_guardian, amountToReduce, _termId);
}
tree.update(guardian.id, nextTermId, _amount, false);
emit GuardianTokensCollected(_guardian, _amount, nextTermId);
return true;
}
/**
* @notice Lock `_guardian`'s withdrawals until term #`_termId`
* @dev This is intended for guardians who voted in a final round and were coherent with the final ruling to prevent 51% attacks
* @param _guardian Address of the guardian to be locked
* @param _termId Term ID until which the guardian's withdrawals will be locked
*/
function lockWithdrawals(address _guardian, uint64 _termId) external onlyActiveDisputeManager {
Guardian storage guardian = guardiansByAddress[_guardian];
guardian.withdrawalsLockTermId = _termId;
}
/**
* @notice Set new limit of total active balance of guardian tokens
* @param _totalActiveBalanceLimit New limit of total active balance of guardian tokens
*/
function setTotalActiveBalanceLimit(uint256 _totalActiveBalanceLimit) external onlyConfigGovernor {
_setTotalActiveBalanceLimit(_totalActiveBalanceLimit);
}
/**
* @dev Tell the total supply of guardian tokens staked
* @return Supply of guardian tokens staked
*/
function totalSupply() external view returns (uint256) {
return guardiansToken.balanceOf(address(this));
}
/**
* @dev Tell the total amount of active guardian tokens
* @return Total amount of active guardian tokens
*/
function totalActiveBalance() external view returns (uint256) {
return tree.getTotal();
}
/**
* @dev Tell the total amount of active guardian tokens for a given term id
* @param _termId Term ID to query on
* @return Total amount of active guardian tokens at the given term id
*/
function totalActiveBalanceAt(uint64 _termId) external view returns (uint256) {
return _totalActiveBalanceAt(_termId);
}
/**
* @dev Tell the total balance of tokens held by a guardian
* This includes the active balance, the available balances, and the pending balance for deactivation.
* Note that we don't have to include the locked balances since these represent the amount of active tokens
* that are locked for drafts, i.e. these are already included in the active balance of the guardian.
* @param _guardian Address of the guardian querying the balance of
* @return Total amount of tokens of a guardian
*/
function balanceOf(address _guardian) external view returns (uint256) {
return _balanceOf(_guardian);
}
/**
* @dev Tell the detailed balance information of a guardian
* @param _guardian Address of the guardian querying the detailed balance information of
* @return active Amount of active tokens of a guardian
* @return available Amount of available tokens of a guardian
* @return locked Amount of active tokens that are locked due to ongoing disputes
* @return pendingDeactivation Amount of active tokens that were requested for deactivation
*/
function detailedBalanceOf(address _guardian) external view
returns (uint256 active, uint256 available, uint256 locked, uint256 pendingDeactivation)
{
return _detailedBalanceOf(_guardian);
}
/**
* @dev Tell the active balance of a guardian for a given term id
* @param _guardian Address of the guardian querying the active balance of
* @param _termId Term ID to query on
* @return Amount of active tokens for guardian in the requested past term id
*/
function activeBalanceOfAt(address _guardian, uint64 _termId) external view returns (uint256) {
return _activeBalanceOfAt(_guardian, _termId);
}
/**
* @dev Tell the amount of active tokens of a guardian at the last ensured term that are not locked due to ongoing disputes
* @param _guardian Address of the guardian querying the unlocked balance of
* @return Amount of active tokens of a guardian that are not locked due to ongoing disputes
*/
function unlockedActiveBalanceOf(address _guardian) external view returns (uint256) {
Guardian storage guardian = guardiansByAddress[_guardian];
return _currentUnlockedActiveBalanceOf(guardian);
}
/**
* @dev Tell the pending deactivation details for a guardian
* @param _guardian Address of the guardian whose info is requested
* @return amount Amount to be deactivated
* @return availableTermId Term in which the deactivated amount will be available
*/
function getDeactivationRequest(address _guardian) external view returns (uint256 amount, uint64 availableTermId) {
DeactivationRequest storage request = guardiansByAddress[_guardian].deactivationRequest;
return (request.amount, request.availableTermId);
}
/**
* @dev Tell the activation amount locked for a guardian by a lock manager
* @param _guardian Address of the guardian whose info is requested
* @param _lockManager Address of the lock manager querying the lock of
* @return amount Activation amount locked by the lock manager
* @return total Total activation amount locked for the guardian
*/
function getActivationLock(address _guardian, address _lockManager) external view returns (uint256 amount, uint256 total) {
ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks;
total = activationLocks.total;
amount = activationLocks.lockedBy[_lockManager];
}
/**
* @dev Tell the withdrawals lock term ID for a guardian
* @param _guardian Address of the guardian whose info is requested
* @return Term ID until which the guardian's withdrawals will be locked
*/
function getWithdrawalsLockTermId(address _guardian) external view returns (uint64) {
return guardiansByAddress[_guardian].withdrawalsLockTermId;
}
/**
* @dev Tell the identification number associated to a guardian address
* @param _guardian Address of the guardian querying the identification number of
* @return Identification number associated to a guardian address, zero in case it wasn't registered yet
*/
function getGuardianId(address _guardian) external view returns (uint256) {
return guardiansByAddress[_guardian].id;
}
/**
* @dev Internal function to activate a given amount of tokens for a guardian.
* This function assumes that the given term is the current term and has already been ensured.
* @param _guardian Address of the guardian to activate tokens
* @param _amount Amount of guardian tokens to be activated
*/
function _activate(address _guardian, uint256 _amount) internal {
uint64 termId = _ensureCurrentTerm();
// Try to clean a previous deactivation request if any
_processDeactivationRequest(_guardian, termId);
uint256 availableBalance = guardiansByAddress[_guardian].availableBalance;
uint256 amountToActivate = _amount == 0 ? availableBalance : _amount;
require(amountToActivate > 0, ERROR_INVALID_ZERO_AMOUNT);
require(amountToActivate <= availableBalance, ERROR_INVALID_ACTIVATION_AMOUNT);
uint64 nextTermId = termId + 1;
_checkTotalActiveBalance(nextTermId, amountToActivate);
Guardian storage guardian = guardiansByAddress[_guardian];
uint256 minActiveBalance = _getMinActiveBalance(nextTermId);
if (_existsGuardian(guardian)) {
// Even though we are adding amounts, let's check the new active balance is greater than or equal to the
// minimum active amount. Note that the guardian might have been slashed.
uint256 activeBalance = tree.getItem(guardian.id);
require(activeBalance.add(amountToActivate) >= minActiveBalance, ERROR_ACTIVE_BALANCE_BELOW_MIN);
tree.update(guardian.id, nextTermId, amountToActivate, true);
} else {
require(amountToActivate >= minActiveBalance, ERROR_ACTIVE_BALANCE_BELOW_MIN);
guardian.id = tree.insert(nextTermId, amountToActivate);
guardiansAddressById[guardian.id] = _guardian;
}
_updateAvailableBalanceOf(_guardian, amountToActivate, false);
emit GuardianActivated(_guardian, nextTermId, amountToActivate);
}
/**
* @dev Internal function to deactivate a given amount of tokens for a guardian.
* @param _guardian Address of the guardian to deactivate tokens
* @param _amount Amount of guardian tokens to be deactivated for the next term
*/
function _deactivate(address _guardian, uint256 _amount) internal {
uint64 termId = _ensureCurrentTerm();
Guardian storage guardian = guardiansByAddress[_guardian];
uint256 unlockedActiveBalance = _lastUnlockedActiveBalanceOf(guardian);
uint256 amountToDeactivate = _amount == 0 ? unlockedActiveBalance : _amount;
require(amountToDeactivate > 0, ERROR_INVALID_ZERO_AMOUNT);
require(amountToDeactivate <= unlockedActiveBalance, ERROR_INVALID_DEACTIVATION_AMOUNT);
// Check future balance is not below the total activation lock of the guardian
// No need for SafeMath: we already checked values above
uint256 futureActiveBalance = unlockedActiveBalance - amountToDeactivate;
uint256 totalActivationLock = guardian.activationLocks.total;
require(futureActiveBalance >= totalActivationLock, ERROR_DEACTIVATION_AMOUNT_EXCEEDS_LOCK);
// Check that the guardian is leaving or that the minimum active balance is met
uint256 minActiveBalance = _getMinActiveBalance(termId);
require(futureActiveBalance == 0 || futureActiveBalance >= minActiveBalance, ERROR_INVALID_DEACTIVATION_AMOUNT);
_createDeactivationRequest(_guardian, amountToDeactivate);
}
/**
* @dev Internal function to create a token deactivation request for a guardian. Guardians will be allowed
* to process a deactivation request from the next term.
* @param _guardian Address of the guardian to create a token deactivation request for
* @param _amount Amount of guardian tokens requested for deactivation
*/
function _createDeactivationRequest(address _guardian, uint256 _amount) internal {
uint64 termId = _ensureCurrentTerm();
// Try to clean a previous deactivation request if possible
_processDeactivationRequest(_guardian, termId);
uint64 nextTermId = termId + 1;
Guardian storage guardian = guardiansByAddress[_guardian];
DeactivationRequest storage request = guardian.deactivationRequest;
request.amount = request.amount.add(_amount);
request.availableTermId = nextTermId;
tree.update(guardian.id, nextTermId, _amount, false);
emit GuardianDeactivationRequested(_guardian, nextTermId, _amount);
}
/**
* @dev Internal function to process a token deactivation requested by a guardian. It will move the requested amount
* to the available balance of the guardian if the term when the deactivation was requested has already finished.
* @param _guardian Address of the guardian to process the deactivation request of
* @param _termId Current term id
*/
function _processDeactivationRequest(address _guardian, uint64 _termId) internal {
Guardian storage guardian = guardiansByAddress[_guardian];
DeactivationRequest storage request = guardian.deactivationRequest;
uint64 deactivationAvailableTermId = request.availableTermId;
// If there is a deactivation request, ensure that the deactivation term has been reached
if (deactivationAvailableTermId == uint64(0) || _termId < deactivationAvailableTermId) {
return;
}
uint256 deactivationAmount = request.amount;
// Note that we can use a zeroed term ID to denote void here since we are storing
// the minimum allowed term to deactivate tokens which will always be at least 1.
request.availableTermId = uint64(0);
request.amount = 0;
_updateAvailableBalanceOf(_guardian, deactivationAmount, true);
emit GuardianDeactivationProcessed(_guardian, deactivationAvailableTermId, deactivationAmount, _termId);
}
/**
* @dev Internal function to reduce a token deactivation requested by a guardian. It assumes the deactivation request
* cannot be processed for the given term yet.
* @param _guardian Address of the guardian to reduce the deactivation request of
* @param _amount Amount to be reduced from the current deactivation request
* @param _termId Term ID in which the deactivation request is being reduced
*/
function _reduceDeactivationRequest(address _guardian, uint256 _amount, uint64 _termId) internal {
Guardian storage guardian = guardiansByAddress[_guardian];
DeactivationRequest storage request = guardian.deactivationRequest;
uint256 currentRequestAmount = request.amount;
require(currentRequestAmount >= _amount, ERROR_CANNOT_REDUCE_DEACTIVATION_REQUEST);
// No need for SafeMath: we already checked values above
uint256 newRequestAmount = currentRequestAmount - _amount;
request.amount = newRequestAmount;
// Move amount back to the tree
tree.update(guardian.id, _termId + 1, _amount, true);
emit GuardianDeactivationUpdated(_guardian, request.availableTermId, newRequestAmount, _termId);
}
/**
* @dev Internal function to update the activation locked amount of a guardian
* @param _guardian Guardian to update the activation locked amount of
* @param _lockManager Address of the lock manager controlling the lock
* @param _amount Amount of tokens to be added to the activation locked amount of the guardian
*/
function _lockActivation(address _guardian, address _lockManager, uint256 _amount) internal {
ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks;
uint256 newTotalLocked = activationLocks.total.add(_amount);
uint256 newLockedAmount = activationLocks.lockedBy[_lockManager].add(_amount);
activationLocks.total = newTotalLocked;
activationLocks.lockedBy[_lockManager] = newLockedAmount;
emit GuardianActivationLockChanged(_guardian, _lockManager, newLockedAmount, newTotalLocked);
}
/**
* @dev Internal function to stake an amount of tokens for a guardian
* @param _guardian Address of the guardian to deposit the tokens to
* @param _amount Amount of tokens to be deposited
*/
function _stake(address _guardian, uint256 _amount) internal {
require(_amount > 0, ERROR_INVALID_ZERO_AMOUNT);
_updateAvailableBalanceOf(_guardian, _amount, true);
emit Staked(_guardian, _amount, _balanceOf(_guardian));
require(guardiansToken.safeTransferFrom(msg.sender, address(this), _amount), ERROR_TOKEN_TRANSFER_FAILED);
}
/**
* @dev Internal function to unstake an amount of tokens of a guardian
* @param _guardian Address of the guardian to to unstake the tokens of
* @param _amount Amount of tokens to be unstaked
*/
function _unstake(address _guardian, uint256 _amount) internal {
require(_amount > 0, ERROR_INVALID_ZERO_AMOUNT);
// Try to process a deactivation request for the current term if there is one. Note that we don't need to ensure
// the current term this time since deactivation requests always work with future terms, which means that if
// the current term is outdated, it will never match the deactivation term id. We avoid ensuring the term here
// to avoid forcing guardians to do that in order to withdraw their available balance. Same applies to final round locks.
uint64 lastEnsuredTermId = _getLastEnsuredTermId();
// Check that guardian's withdrawals are not locked
uint64 withdrawalsLockTermId = guardiansByAddress[_guardian].withdrawalsLockTermId;
require(withdrawalsLockTermId == 0 || withdrawalsLockTermId < lastEnsuredTermId, ERROR_WITHDRAWALS_LOCK);
_processDeactivationRequest(_guardian, lastEnsuredTermId);
_updateAvailableBalanceOf(_guardian, _amount, false);
emit Unstaked(_guardian, _amount, _balanceOf(_guardian));
require(guardiansToken.safeTransfer(_guardian, _amount), ERROR_TOKEN_TRANSFER_FAILED);
}
/**
* @dev Internal function to update the available balance of a guardian
* @param _guardian Guardian to update the available balance of
* @param _amount Amount of tokens to be added to or removed from the available balance of a guardian
* @param _positive True if the given amount should be added, or false to remove it from the available balance
*/
function _updateAvailableBalanceOf(address _guardian, uint256 _amount, bool _positive) internal {
// We are not using a require here to avoid reverting in case any of the treasury maths reaches this point
// with a zeroed amount value. Instead, we are doing this validation in the external entry points such as
// stake, unstake, activate, deactivate, among others.
if (_amount == 0) {
return;
}
Guardian storage guardian = guardiansByAddress[_guardian];
if (_positive) {
guardian.availableBalance = guardian.availableBalance.add(_amount);
} else {
require(_amount <= guardian.availableBalance, ERROR_NOT_ENOUGH_AVAILABLE_BALANCE);
// No need for SafeMath: we already checked values right above
guardian.availableBalance -= _amount;
}
}
/**
* @dev Internal function to set new limit of total active balance of guardian tokens
* @param _totalActiveBalanceLimit New limit of total active balance of guardian tokens
*/
function _setTotalActiveBalanceLimit(uint256 _totalActiveBalanceLimit) internal {
require(_totalActiveBalanceLimit > 0, ERROR_BAD_TOTAL_ACTIVE_BALANCE_LIMIT);
emit TotalActiveBalanceLimitChanged(totalActiveBalanceLimit, _totalActiveBalanceLimit);
totalActiveBalanceLimit = _totalActiveBalanceLimit;
}
/**
* @dev Internal function to tell the total balance of tokens held by a guardian
* @param _guardian Address of the guardian querying the total balance of
* @return Total amount of tokens of a guardian
*/
function _balanceOf(address _guardian) internal view returns (uint256) {
(uint256 active, uint256 available, , uint256 pendingDeactivation) = _detailedBalanceOf(_guardian);
return available.add(active).add(pendingDeactivation);
}
/**
* @dev Internal function to tell the detailed balance information of a guardian
* @param _guardian Address of the guardian querying the balance information of
* @return active Amount of active tokens of a guardian
* @return available Amount of available tokens of a guardian
* @return locked Amount of active tokens that are locked due to ongoing disputes
* @return pendingDeactivation Amount of active tokens that were requested for deactivation
*/
function _detailedBalanceOf(address _guardian) internal view
returns (uint256 active, uint256 available, uint256 locked, uint256 pendingDeactivation)
{
Guardian storage guardian = guardiansByAddress[_guardian];
active = _existsGuardian(guardian) ? tree.getItem(guardian.id) : 0;
(available, locked, pendingDeactivation) = _getBalances(guardian);
}
/**
* @dev Tell the active balance of a guardian for a given term id
* @param _guardian Address of the guardian querying the active balance of
* @param _termId Term ID querying the active balance for
* @return Amount of active tokens for guardian in the requested past term id
*/
function _activeBalanceOfAt(address _guardian, uint64 _termId) internal view returns (uint256) {
Guardian storage guardian = guardiansByAddress[_guardian];
return _existsGuardian(guardian) ? tree.getItemAt(guardian.id, _termId) : 0;
}
/**
* @dev Internal function to get the amount of active tokens of a guardian that are not locked due to ongoing disputes
* It will use the last value, that might be in a future term
* @param _guardian Guardian querying the unlocked active balance of
* @return Amount of active tokens of a guardian that are not locked due to ongoing disputes
*/
function _lastUnlockedActiveBalanceOf(Guardian storage _guardian) internal view returns (uint256) {
return _existsGuardian(_guardian) ? tree.getItem(_guardian.id).sub(_guardian.lockedBalance) : 0;
}
/**
* @dev Internal function to get the amount of active tokens at the last ensured term of a guardian that are not locked due to ongoing disputes
* @param _guardian Guardian querying the unlocked active balance of
* @return Amount of active tokens of a guardian that are not locked due to ongoing disputes
*/
function _currentUnlockedActiveBalanceOf(Guardian storage _guardian) internal view returns (uint256) {
uint64 lastEnsuredTermId = _getLastEnsuredTermId();
return _existsGuardian(_guardian) ? tree.getItemAt(_guardian.id, lastEnsuredTermId).sub(_guardian.lockedBalance) : 0;
}
/**
* @dev Internal function to check if a guardian was already registered
* @param _guardian Guardian to be checked
* @return True if the given guardian was already registered, false otherwise
*/
function _existsGuardian(Guardian storage _guardian) internal view returns (bool) {
return _guardian.id != 0;
}
/**
* @dev Internal function to get the amount of a deactivation request for a given term id
* @param _guardian Guardian to query the deactivation request amount of
* @param _termId Term ID of the deactivation request to be queried
* @return Amount of the deactivation request for the given term, 0 otherwise
*/
function _deactivationRequestedAmountForTerm(Guardian storage _guardian, uint64 _termId) internal view returns (uint256) {
DeactivationRequest storage request = _guardian.deactivationRequest;
return request.availableTermId == _termId ? request.amount : 0;
}
/**
* @dev Internal function to tell the total amount of active guardian tokens at the given term id
* @param _termId Term ID querying the total active balance for
* @return Total amount of active guardian tokens at the given term id
*/
function _totalActiveBalanceAt(uint64 _termId) internal view returns (uint256) {
// This function will return always the same values, the only difference remains on gas costs. In case we look for a
// recent term, in this case current or future ones, we perform a backwards linear search from the last checkpoint.
// Otherwise, a binary search is computed.
bool recent = _termId >= _getLastEnsuredTermId();
return recent ? tree.getRecentTotalAt(_termId) : tree.getTotalAt(_termId);
}
/**
* @dev Internal function to check if its possible to add a given new amount to the registry or not
* @param _termId Term ID when the new amount will be added
* @param _amount Amount of tokens willing to be added to the registry
*/
function _checkTotalActiveBalance(uint64 _termId, uint256 _amount) internal view {
uint256 currentTotalActiveBalance = _totalActiveBalanceAt(_termId);
uint256 newTotalActiveBalance = currentTotalActiveBalance.add(_amount);
require(newTotalActiveBalance <= totalActiveBalanceLimit, ERROR_TOTAL_ACTIVE_BALANCE_EXCEEDED);
}
/**
* @dev Tell the local balance information of a guardian (that is not on the tree)
* @param _guardian Address of the guardian querying the balance information of
* @return available Amount of available tokens of a guardian
* @return locked Amount of active tokens that are locked due to ongoing disputes
* @return pendingDeactivation Amount of active tokens that were requested for deactivation
*/
function _getBalances(Guardian storage _guardian) internal view returns (uint256 available, uint256 locked, uint256 pendingDeactivation) {
available = _guardian.availableBalance;
locked = _guardian.lockedBalance;
pendingDeactivation = _guardian.deactivationRequest.amount;
}
/**
* @dev Internal function to search guardians in the tree based on certain search restrictions
* @param _params Draft params to be used for the guardians search
* @return ids List of guardian ids obtained based on the requested search
* @return activeBalances List of active balances for each guardian obtained based on the requested search
*/
function _treeSearch(DraftParams memory _params) internal view returns (uint256[] memory ids, uint256[] memory activeBalances) {
(ids, activeBalances) = tree.batchedRandomSearch(
_params.termRandomness,
_params.disputeId,
_params.termId,
_params.selectedGuardians,
_params.batchRequestedGuardians,
_params.roundRequestedGuardians,
_params.iteration
);
}
/**
* @dev Private function to parse a certain set given of draft params
* @param _params Array containing draft requirements:
* 0. bytes32 Term randomness
* 1. uint256 Dispute id
* 2. uint64 Current term id
* 3. uint256 Number of seats already filled
* 4. uint256 Number of seats left to be filled
* 5. uint64 Number of guardians required for the draft
* 6. uint16 Permyriad of the minimum active balance to be locked for the draft
*
* @return Draft params object parsed
*/
function _buildDraftParams(uint256[7] memory _params) private view returns (DraftParams memory) {
uint64 termId = uint64(_params[2]);
uint256 minActiveBalance = _getMinActiveBalance(termId);
return DraftParams({
termRandomness: bytes32(_params[0]),
disputeId: _params[1],
termId: termId,
selectedGuardians: _params[3],
batchRequestedGuardians: _params[4],
roundRequestedGuardians: _params[5],
draftLockAmount: minActiveBalance.pct(uint16(_params[6])),
iteration: 0
});
}
} | Minimum amount of tokens guardians have to activate to participate in the Court
| uint256 minActiveBalance; | 91,652 | [
1,
13042,
3844,
434,
2430,
11026,
19657,
1240,
358,
10235,
358,
30891,
340,
316,
326,
385,
477,
88,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2254,
5034,
1131,
3896,
13937,
31,
7734,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.6.0;
import "./Owned.sol";
import "./BREE.sol";
import "./ERC20contract.sol";
import "./SafeMath.sol";
contract BREE_STAKE_FARM is Owned{
using SafeMath for uint256;
uint256 public yieldCollectionFee = 0.01 ether;
uint256 public stakingPeriod = 30 days;
uint256 public stakeClaimFee = 0.001 ether;
uint256 public totalYield;
uint256 public totalRewards;
Token public bree;
struct Tokens{
bool exists;
uint256 rate;
}
mapping(address => Tokens) public tokens;
address[] TokensAddresses;
struct DepositedToken{
bool whitelisted;
uint256 activeDeposit;
uint256 totalDeposits;
uint256 startTime;
uint256 pendingGains;
uint256 lastClaimedDate;
uint256 totalGained;
uint rate;
uint period;
}
mapping(address => mapping(address => DepositedToken)) users;
event TokenAdded(address tokenAddress, uint256 APY);
event TokenRemoved(address tokenAddress);
event FarmingRateChanged(address tokenAddress, uint256 newAPY);
event YieldCollectionFeeChanged(uint256 yieldCollectionFee);
event FarmingStarted(address _tokenAddress, uint256 _amount);
event YieldCollected(address _tokenAddress, uint256 _yield);
event AddedToExistingFarm(address _tokenAddress, uint256 tokens);
event Staked(address staker, uint256 tokens);
event AddedToExistingStake(uint256 tokens);
event StakingRateChanged(uint256 newAPY);
event TokensClaimed(address claimer, uint256 stakedTokens);
event RewardClaimed(address claimer, uint256 reward);
modifier isWhitelisted(address _account){
require(users[_account][address(bree)].whitelisted, "user is not whitelisted");
_;
}
constructor(address _tokenAddress) public {
bree = Token(_tokenAddress);
// add bree token to ecosystem
_addToken(_tokenAddress, 40); // 40 apy initially
}
//#########################################################################################################################################################//
//####################################################FARMING EXTERNAL FUNCTIONS###########################################################################//
//#########################################################################################################################################################//
// ------------------------------------------------------------------------
// Add assets to farm
// @param _tokenAddress address of the token asset
// @param _amount amount of tokens to deposit
// ------------------------------------------------------------------------
function FARM(address _tokenAddress, uint256 _amount) public{
require(_tokenAddress != address(bree), "Use staking instead");
// add to farm
_newDeposit(_tokenAddress, _amount);
// transfer tokens from user to the contract balance
ERC20Interface(_tokenAddress).transferFrom(msg.sender, address(this), _amount);
emit FarmingStarted(_tokenAddress, _amount);
}
// ------------------------------------------------------------------------
// Add more deposits to already running farm
// @param _tokenAddress address of the token asset
// @param _amount amount of tokens to deposit
// ------------------------------------------------------------------------
function addToFarm(address _tokenAddress, uint256 _amount) public{
require(_tokenAddress != address(bree), "use staking instead");
_addToExisting(_tokenAddress, _amount);
// move the tokens from the caller to the contract address
ERC20Interface(_tokenAddress).transferFrom(msg.sender,address(this), _amount);
emit AddedToExistingFarm(_tokenAddress, _amount);
}
// ------------------------------------------------------------------------
// Withdraw accumulated yield
// @param _tokenAddress address of the token asset
// @required must pay yield claim fee
// ------------------------------------------------------------------------
function YIELD(address _tokenAddress) public payable {
require(msg.value >= yieldCollectionFee, "should pay exact claim fee");
require(pendingYield(_tokenAddress, msg.sender) > 0, "No pending yield");
require(tokens[_tokenAddress].exists, "Token doesn't exist");
// transfer fee to the owner
owner.transfer(msg.value);
// mint more tokens inside token contract
bree.mintTokens(pendingYield(_tokenAddress, msg.sender), msg.sender);
emit YieldCollected(_tokenAddress, pendingYield(_tokenAddress, msg.sender));
// Global stats update
totalYield += pendingYield(_tokenAddress, msg.sender);
// update the record
users[msg.sender][_tokenAddress].totalGained += pendingYield(_tokenAddress, msg.sender);
users[msg.sender][_tokenAddress].lastClaimedDate = now;
users[msg.sender][_tokenAddress].pendingGains = 0;
}
// ------------------------------------------------------------------------
// Withdraw any amount of tokens, the contract will update the farming
// @param _tokenAddress address of the token asset
// @param _amount amount of tokens to deposit
// ------------------------------------------------------------------------
function withdrawFarmedTokens(address _tokenAddress, uint256 _amount) public {
require(tokens[_tokenAddress].exists, "Token doesn't exist");
require(users[msg.sender][_tokenAddress].activeDeposit >= _amount, "insufficient amount in farming");
// withdraw the tokens and move from contract to the caller
ERC20Interface(_tokenAddress).transfer(msg.sender, _amount);
// update farming stats
// check if we have any pending yield, add it to previousYield var
users[msg.sender][_tokenAddress].pendingGains = pendingYield(_tokenAddress, msg.sender);
// update amount
users[msg.sender][_tokenAddress].activeDeposit -= _amount;
// update farming start time -- new farming will begin from this time onwards
users[msg.sender][_tokenAddress].startTime = now;
// reset last claimed figure as well -- new farming will begin from this time onwards
users[msg.sender][_tokenAddress].lastClaimedDate = now;
emit TokensClaimed(msg.sender, _amount);
}
//#########################################################################################################################################################//
//####################################################STAKING EXTERNAL FUNCTIONS###########################################################################//
//#########################################################################################################################################################//
// ------------------------------------------------------------------------
// Start staking
// @param _tokenAddress address of the token asset
// @param _amount amount of tokens to deposit
// ------------------------------------------------------------------------
function STAKE(uint256 _amount) public isWhitelisted(msg.sender) {
// add new stake
_newDeposit(address(bree), _amount);
// transfer tokens from user to the contract balance
bree.transferFrom(msg.sender, address(this), _amount);
emit Staked(msg.sender, _amount);
}
// ------------------------------------------------------------------------
// Add more deposits to already running farm
// @param _tokenAddress address of the token asset
// @param _amount amount of tokens to deposit
// ------------------------------------------------------------------------
function addToStake(uint256 _amount) public {
require(now - users[msg.sender][address(bree)].startTime < users[msg.sender][address(bree)].period, "current staking expired");
_addToExisting(address(bree), _amount);
// move the tokens from the caller to the contract address
bree.transferFrom(msg.sender,address(this), _amount);
emit AddedToExistingStake(_amount);
}
// ------------------------------------------------------------------------
// Claim reward and staked tokens
// @required user must be a staker
// @required must be claimable
// ------------------------------------------------------------------------
function ClaimStakedTokens() external {
//require(users[msg.sender][address(bree)].running, "no running stake");
require(users[msg.sender][address(bree)].activeDeposit > 0, "no running stake");
require(users[msg.sender][address(bree)].startTime + users[msg.sender][address(bree)].period < now, "not claimable before staking period");
// transfer staked tokens
bree.transfer(msg.sender, users[msg.sender][address(bree)].activeDeposit);
// check if we have any pending reward, add it to pendingGains var
users[msg.sender][address(bree)].pendingGains = pendingReward(msg.sender);
// update amount
users[msg.sender][address(bree)].activeDeposit = 0;
emit TokensClaimed(msg.sender, users[msg.sender][address(bree)].activeDeposit);
}
// ------------------------------------------------------------------------
// Claim reward and staked tokens
// @required user must be a staker
// @required must be claimable
// ------------------------------------------------------------------------
function ClaimReward() external payable {
require(msg.value >= stakeClaimFee, "should pay exact claim fee");
require(pendingReward(msg.sender) > 0, "nothing pending to claim");
// mint more tokens inside token contract
bree.mintTokens(pendingReward(msg.sender), msg.sender);
emit RewardClaimed(msg.sender, pendingReward(msg.sender));
// add claimed reward to global stats
totalRewards += pendingReward(msg.sender);
// add the reward to total claimed rewards
users[msg.sender][address(bree)].totalGained += pendingReward(msg.sender);
// update lastClaim amount
users[msg.sender][address(bree)].lastClaimedDate = now;
// reset previous rewards
users[msg.sender][address(bree)].pendingGains = 0;
// transfer the claim fee to the owner
owner.transfer(msg.value);
}
//#########################################################################################################################################################//
//##########################################################FARMING QUERIES################################################################################//
//#########################################################################################################################################################//
// ------------------------------------------------------------------------
// Query to get the pending yield
// @param _tokenAddress address of the token asset
// ------------------------------------------------------------------------
function pendingYield(address _tokenAddress, address _caller) public view returns(uint256 _pendingRewardWeis){
uint256 _totalFarmingTime = now.sub(users[_caller][_tokenAddress].lastClaimedDate);
uint256 _reward_token_second = ((tokens[_tokenAddress].rate).mul(10 ** 21)).div(365 days); // added extra 10^21
uint256 yield = ((users[_caller][_tokenAddress].activeDeposit).mul(_totalFarmingTime.mul(_reward_token_second))).div(10 ** 23); // remove extra 10^21 // 10^2 are for 100 (%)
return yield.add(users[_caller][_tokenAddress].pendingGains);
}
// ------------------------------------------------------------------------
// Query to get the active farm of the user
// @param farming asset/ token address
// ------------------------------------------------------------------------
function activeFarmDeposit(address _tokenAddress, address _user) public view returns(uint256 _activeDeposit){
return users[_user][_tokenAddress].activeDeposit;
}
// ------------------------------------------------------------------------
// Query to get the total farming of the user
// @param farming asset/ token address
// ------------------------------------------------------------------------
function yourTotalFarmingTillToday(address _tokenAddress, address _user) public view returns(uint256 _totalFarming){
return users[_user][_tokenAddress].totalDeposits;
}
// ------------------------------------------------------------------------
// Query to get the time of last farming of user
// ------------------------------------------------------------------------
function lastFarmedOn(address _tokenAddress, address _user) public view returns(uint256 _unixLastFarmedTime){
return users[_user][_tokenAddress].startTime;
}
// ------------------------------------------------------------------------
// Query to get total earned rewards from particular farming
// @param farming asset/ token address
// ------------------------------------------------------------------------
function totalFarmingRewards(address _tokenAddress, address _user) public view returns(uint256 _totalEarned){
return users[_user][_tokenAddress].totalGained;
}
//#########################################################################################################################################################//
//####################################################FARMING ONLY OWNER FUNCTIONS#########################################################################//
//#########################################################################################################################################################//
// ------------------------------------------------------------------------
// Add supported tokens
// @param _tokenAddress address of the token asset
// @param _farmingRate rate applied for farming yield to produce
// @required only owner
// ------------------------------------------------------------------------
function addToken(address _tokenAddress, uint256 _rate) public onlyOwner {
_addToken(_tokenAddress, _rate);
}
// ------------------------------------------------------------------------
// Remove tokens if no longer supported
// @param _tokenAddress address of the token asset
// @required only owner
// ------------------------------------------------------------------------
function removeToken(address _tokenAddress) public onlyOwner {
require(tokens[_tokenAddress].exists, "token doesn't exist");
tokens[_tokenAddress].exists = false;
emit TokenRemoved(_tokenAddress);
}
// ------------------------------------------------------------------------
// Change farming rate of the supported token
// @param _tokenAddress address of the token asset
// @param _newFarmingRate new rate applied for farming yield to produce
// @required only owner
// ------------------------------------------------------------------------
function changeFarmingRate(address _tokenAddress, uint256 _newFarmingRate) public onlyOwner {
require(tokens[_tokenAddress].exists, "token doesn't exist");
tokens[_tokenAddress].rate = _newFarmingRate;
emit FarmingRateChanged(_tokenAddress, _newFarmingRate);
}
// ------------------------------------------------------------------------
// Change Yield collection fee
// @param _fee fee to claim the yield
// @required only owner
// ------------------------------------------------------------------------
function setYieldCollectionFee(uint256 _fee) public{
yieldCollectionFee = _fee;
emit YieldCollectionFeeChanged(_fee);
}
//#########################################################################################################################################################//
//####################################################STAKING QUERIES######################################################################################//
//#########################################################################################################################################################//
// ------------------------------------------------------------------------
// Query to get the pending reward
// ------------------------------------------------------------------------
function pendingReward(address _caller) public view returns(uint256 _pendingReward){
uint256 _totalStakedTime = 0;
uint256 expiryDate = (users[_caller][address(bree)].period).add(users[_caller][address(bree)].startTime);
if(now < expiryDate)
_totalStakedTime = now.sub(users[_caller][address(bree)].lastClaimedDate);
else{
if(users[_caller][address(bree)].lastClaimedDate >= expiryDate) // if claimed after expirydate already
_totalStakedTime = 0;
else
_totalStakedTime = expiryDate.sub(users[_caller][address(bree)].lastClaimedDate);
}
uint256 _reward_token_second = ((users[_caller][address(bree)].rate).mul(10 ** 21)).div(365 days); // added extra 10^21
uint256 reward = ((users[_caller][address(bree)].activeDeposit).mul(_totalStakedTime.mul(_reward_token_second))).div(10 ** 23); // remove extra 10^21 // the two extra 10^2 is for 100 (%)
return (reward.add(users[_caller][address(bree)].pendingGains));
}
// ------------------------------------------------------------------------
// Query to get the active stake of the user
// ------------------------------------------------------------------------
function yourActiveStake(address _user) public view returns(uint256 _activeStake){
return users[_user][address(bree)].activeDeposit;
}
// ------------------------------------------------------------------------
// Query to get the total stakes of the user
// ------------------------------------------------------------------------
function yourTotalStakesTillToday(address _user) public view returns(uint256 _totalStakes){
return users[_user][address(bree)].totalDeposits;
}
// ------------------------------------------------------------------------
// Query to get the time of last stake of user
// ------------------------------------------------------------------------
function lastStakedOn(address _user) public view returns(uint256 _unixLastStakedTime){
return users[_user][address(bree)].startTime;
}
// ------------------------------------------------------------------------
// Query to get if user is whitelisted for staking or not
// ------------------------------------------------------------------------
function isUserWhitelisted(address _user) public view returns(bool _result){
return users[_user][address(bree)].whitelisted;
}
// ------------------------------------------------------------------------
// Query to get total earned rewards from stake
// ------------------------------------------------------------------------
function totalStakeRewardsClaimedTillToday(address _user) public view returns(uint256 _totalEarned){
return users[_user][address(bree)].totalGained;
}
// ------------------------------------------------------------------------
// Query to get the staking rate
// ------------------------------------------------------------------------
function latestStakingRate() public view returns(uint256 APY){
return tokens[address(bree)].rate;
}
// ------------------------------------------------------------------------
// Query to get the staking rate you staked at
// ------------------------------------------------------------------------
function yourStakingRate(address _user) public view returns(uint256 _stakingRate){
return users[_user][address(bree)].rate;
}
// ------------------------------------------------------------------------
// Query to get the staking period you staked at
// ------------------------------------------------------------------------
function yourStakingPeriod(address _user) public view returns(uint256 _stakingPeriod){
return users[_user][address(bree)].period;
}
// ------------------------------------------------------------------------
// Query to get the staking time left
// ------------------------------------------------------------------------
function stakingTimeLeft(address _user) public view returns(uint256 _secsLeft){
uint256 left = 0;
uint256 expiryDate = (users[_user][address(bree)].period).add(lastStakedOn(_user));
if(now < expiryDate)
left = expiryDate.sub(now);
return left;
}
//#########################################################################################################################################################//
//####################################################STAKING ONLY OWNER FUNCTION##########################################################################//
//#########################################################################################################################################################//
// ------------------------------------------------------------------------
// Change staking rate
// @param _newStakingRate new rate applied for staking
// @required only owner
// ------------------------------------------------------------------------
function changeStakingRate(uint256 _newStakingRate) public onlyOwner{
tokens[address(bree)].rate = _newStakingRate;
emit StakingRateChanged(_newStakingRate);
}
// ------------------------------------------------------------------------
// Add accounts to the white list
// @param _account the address of the account to be added to the whitelist
// @required only callable by owner
// ------------------------------------------------------------------------
function whiteList(address _account) public onlyOwner{
users[_account][address(bree)].whitelisted = true;
}
// ------------------------------------------------------------------------
// Change the staking period
// @param _seconds number of seconds to stake (n days = n*24*60*60)
// @required only callable by owner
// ------------------------------------------------------------------------
function setStakingPeriod(uint256 _seconds) public onlyOwner{
stakingPeriod = _seconds;
}
// ------------------------------------------------------------------------
// Change the staking claim fee
// @param _fee claim fee in weis
// @required only callable by owner
// ------------------------------------------------------------------------
function setClaimFee(uint256 _fee) public onlyOwner{
stakeClaimFee = _fee;
}
//#########################################################################################################################################################//
//################################################################COMMON UTILITIES#########################################################################//
//#########################################################################################################################################################//
// ------------------------------------------------------------------------
// Internal function to add new deposit
// ------------------------------------------------------------------------
function _newDeposit(address _tokenAddress, uint256 _amount) internal{
require(users[msg.sender][_tokenAddress].activeDeposit == 0, "Already running");
require(tokens[_tokenAddress].exists, "Token doesn't exist");
// add that token into the contract balance
// check if we have any pending reward/yield, add it to pendingGains variable
if(_tokenAddress == address(bree)){
users[msg.sender][_tokenAddress].pendingGains = pendingReward(msg.sender);
users[msg.sender][_tokenAddress].period = stakingPeriod;
users[msg.sender][_tokenAddress].rate = tokens[_tokenAddress].rate; // rate for stakers will be fixed at time of staking
}
else
users[msg.sender][_tokenAddress].pendingGains = pendingYield(_tokenAddress, msg.sender);
users[msg.sender][_tokenAddress].activeDeposit = _amount;
users[msg.sender][_tokenAddress].totalDeposits += _amount;
users[msg.sender][_tokenAddress].startTime = now;
users[msg.sender][_tokenAddress].lastClaimedDate = now;
}
// ------------------------------------------------------------------------
// Internal function to add to existing deposit
// ------------------------------------------------------------------------
function _addToExisting(address _tokenAddress, uint256 _amount) internal{
require(tokens[_tokenAddress].exists, "Token doesn't exist");
// require(users[msg.sender][_tokenAddress].running, "no running farming/stake");
require(users[msg.sender][_tokenAddress].activeDeposit > 0, "no running farming/stake");
// update farming stats
// check if we have any pending reward/yield, add it to pendingGains variable
if(_tokenAddress == address(bree)){
users[msg.sender][_tokenAddress].pendingGains = pendingReward(msg.sender);
users[msg.sender][_tokenAddress].period = stakingPeriod;
users[msg.sender][_tokenAddress].rate = tokens[_tokenAddress].rate; // rate of only staking will be updated when more is added to stake
}
else
users[msg.sender][_tokenAddress].pendingGains = pendingYield(_tokenAddress, msg.sender);
// update current deposited amount
users[msg.sender][_tokenAddress].activeDeposit += _amount;
// update total deposits till today
users[msg.sender][_tokenAddress].totalDeposits += _amount;
// update new deposit start time -- new stake/farming will begin from this time onwards
users[msg.sender][_tokenAddress].startTime = now;
// reset last claimed figure as well -- new stake/farming will begin from this time onwards
users[msg.sender][_tokenAddress].lastClaimedDate = now;
}
// ------------------------------------------------------------------------
// Internal function to add token
// ------------------------------------------------------------------------
function _addToken(address _tokenAddress, uint256 _rate) internal{
require(!tokens[_tokenAddress].exists, "token already exists");
tokens[_tokenAddress] = Tokens({
exists: true,
rate: _rate
});
TokensAddresses.push(_tokenAddress);
emit TokenAdded(_tokenAddress, _rate);
}
}
| update current deposited amount | users[msg.sender][_tokenAddress].activeDeposit += _amount;
| 987,969 | [
1,
2725,
783,
443,
1724,
329,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5411,
3677,
63,
3576,
18,
15330,
6362,
67,
2316,
1887,
8009,
3535,
758,
1724,
1011,
389,
8949,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
* @title: Idle Token Bootstrap contract
* @summary: Used to deploy a new instance of an idleToken. The contract will then
* be upgraded to IdleTokenGovernance
* @author: Idle Labs Inc., idle.finance
*/
pragma solidity 0.5.16;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Detailed.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/lifecycle/Pausable.sol";
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "./interfaces/iERC20Fulcrum.sol";
import "./interfaces/ILendingProtocol.sol";
import "./interfaces/IGovToken.sol";
import "./interfaces/IIdleTokenV3_1.sol";
import "./interfaces/IERC3156FlashBorrower.sol";
import "./interfaces/Comptroller.sol";
import "./interfaces/CERC20.sol";
import "./interfaces/IdleController.sol";
import "./interfaces/PriceOracle.sol";
import "./interfaces/IUniswapV2Router02.sol";
import "./interfaces/IIdleTokenHelper.sol";
import "./GST2ConsumerV2.sol";
contract IdleTokenV3_1 is Initializable, ERC20, ERC20Detailed, ReentrancyGuard, Ownable, Pausable, IIdleTokenV3_1, GST2ConsumerV2 {
using SafeERC20 for IERC20;
using SafeMath for uint256;
uint256 private constant ONE_18 = 10**18;
// State variables
// eg. DAI address
address public token;
// eg. iDAI address
address private iToken;
// eg. cDAI address
address private cToken;
// Idle rebalancer current implementation address
address public rebalancer;
// Address collecting underlying fees
address public feeAddress;
// Last iToken price, used to pause contract in case of a black swan event
uint256 public lastITokenPrice;
// eg. 18 for DAI
uint256 private tokenDecimals;
// Max unlent assets percentage for gas friendly swaps
uint256 public maxUnlentPerc; // 100000 == 100% -> 1000 == 1%
// Current fee on interest gained
uint256 public fee;
// eg. [cTokenAddress, iTokenAddress, ...]
address[] public allAvailableTokens;
// eg. [COMPAddress, CRVAddress, ...]
address[] public govTokens;
// last fully applied allocations (ie when all liquidity has been correctly placed)
// eg. [5000, 0, 5000, 0] for 50% in compound, 0% fulcrum, 50% aave, 0 dydx. same order of allAvailableTokens
uint256[] public lastAllocations;
// Map that saves avg idleToken price paid for each user, used to calculate earnings
mapping(address => uint256) public userAvgPrices;
// eg. cTokenAddress => IdleCompoundAddress
mapping(address => address) public protocolWrappers;
// array with last balance recorded for each gov tokens
mapping (address => uint256) public govTokensLastBalances;
// govToken -> user_address -> user_index eg. usersGovTokensIndexes[govTokens[0]][msg.sender] = 1111123;
mapping (address => mapping (address => uint256)) public usersGovTokensIndexes;
// global indices for each gov tokens used as a reference to calculate a fair share for each user
mapping (address => uint256) public govTokensIndexes;
// Map that saves amount with no fee for each user
mapping(address => uint256) private userNoFeeQty;
// variable used for avoid the call of mint and redeem in the same tx
bytes32 private _minterBlock;
// Events
event Rebalance(address _rebalancer, uint256 _amount);
event Referral(uint256 _amount, address _ref);
// ########## IdleToken V4_1 updates
// Idle governance token
address public constant IDLE = address(0x875773784Af8135eA0ef43b5a374AaD105c5D39e);
// Compound governance token
address public constant COMP = address(0xc00e94Cb662C3520282E6f5717214004A7f26888);
uint256 private constant FULL_ALLOC = 100000;
// Idle distribution controller
address public constant idleController = address(0x275DA8e61ea8E02d51EDd8d0DC5c0E62b4CDB0BE);
// oracle used for calculating the avgAPR with gov tokens
address public oracle;
// eg cDAI -> COMP
mapping(address => address) private protocolTokenToGov;
// Whether openRebalance is enabled or not
bool public isRiskAdjusted;
// last allocations submitted by rebalancer
uint256[] private lastRebalancerAllocations;
// ########## IdleToken V5 updates
// Fee for flash loan
uint256 public flashLoanFee;
// IdleToken helper address
address public tokenHelper;
/**
* @dev Emitted on flashLoan()
* @param target The address of the flash loan receiver contract
* @param initiator The address initiating the flash loan
* @param amount The amount flash borrowed
* @param premium The fee flash borrowed
**/
event FlashLoan(
address indexed target,
address indexed initiator,
uint256 amount,
uint256 premium
);
// Addresses for stkAAVE distribution from Aave
address public constant stkAAVE = address(0x4da27a545c0c5B758a6BA100e3a049001de870f5);
address private aToken;
// ####################################################
// ################# INIT METHODS #####################
// ####################################################
/**
* It allows owner to manually initialize new contract implementation which supports IDLE distribution
*
* @param _newGovTokens : array of gov token addresses
* @param _protocolTokens : array of protocol tokens supported
* @param _wrappers : array of wrappers for protocol tokens
* @param _lastRebalancerAllocations : array of allocations
* @param _isRiskAdjusted : flag whether is risk adjusted or not
*/
function manualInitialize(
address[] calldata _newGovTokens,
address[] calldata _protocolTokens,
address[] calldata _wrappers,
uint256[] calldata _lastRebalancerAllocations,
bool _isRiskAdjusted,
address _cToken,
address _aToken
) external onlyOwner {
cToken = _cToken;
aToken = _aToken;
isRiskAdjusted = _isRiskAdjusted;
// set all available tokens and set the protocolWrappers mapping in the for loop
allAvailableTokens = _protocolTokens;
// same as setGovTokens, copied to avoid make the method public and save on bytecode size
govTokens = _newGovTokens;
// set protocol token to gov token mapping
for (uint256 i = 0; i < _protocolTokens.length; i++) {
protocolWrappers[_protocolTokens[i]] = _wrappers[i];
if (i < _newGovTokens.length) {
if (_newGovTokens[i] == IDLE) { continue; }
protocolTokenToGov[_protocolTokens[i]] = _newGovTokens[i];
}
}
lastRebalancerAllocations = _lastRebalancerAllocations;
lastAllocations = _lastRebalancerAllocations;
// Idle multisig
addPauser(address(0xaDa343Cb6820F4f5001749892f6CAA9920129F2A));
// Remove pause ability from msg.sender
renouncePauser();
}
function _init(
string calldata _name, // eg. IdleDAI
string calldata _symbol, // eg. IDLEDAI
address _token
) external initializer {
// copied from old initialize() method removed at commit 04e29bd6f9282ef5677edc16570918da1a72dd3a
// Initialize inherited contracts
ERC20Detailed.initialize(_name, _symbol, 18);
Ownable.initialize(msg.sender);
Pausable.initialize(msg.sender);
ReentrancyGuard.initialize();
// Initialize storage variables
maxUnlentPerc = 1000;
flashLoanFee = 80;
token = _token;
tokenDecimals = ERC20Detailed(_token).decimals();
// end of old initialize method
oracle = address(0xB5A8f07dD4c3D315869405d702ee8F6EA695E8C5);
feeAddress = address(0xBecC659Bfc6EDcA552fa1A67451cC6b38a0108E4);
rebalancer = address(0xB3C8e5534F0063545CBbb7Ce86854Bf42dB8872B);
tokenHelper = address(0x5B7400cC634a49650Cb3212D882512424fED00ed);
fee = 10000;
iToken = address(0);
}
// ####################################################
// ############### END INIT METHODS ###################
// ####################################################
// Contract interfact for IIdleTokenV3_1
// view
/**
* Get latest allocations submitted by rebalancer
*
* @return : array of allocations ordered as allAvailableTokens
*/
function getAllocations() external view returns (uint256[] memory) {
return lastRebalancerAllocations;
}
/**
* Get currently used gov tokens
*
* @return : array of govTokens supported
*/
function getGovTokens() external view returns (address[] memory) {
return govTokens;
}
/**
* Get currently used protocol tokens (cDAI, aDAI, ...)
*
* @return : array of protocol tokens supported
*/
function getAllAvailableTokens() external view returns (address[] memory) {
return allAvailableTokens;
}
/**
* Get gov token associated to a protocol token eg protocolTokenToGov[cDAI] = COMP
*
* @return : address of the gov token
*/
function getProtocolTokenToGov(address _protocolToken) external view returns (address) {
return protocolTokenToGov[_protocolToken];
}
/**
* IdleToken price calculation, in underlying
*
* @return : price in underlying token
*/
function tokenPrice() external view returns (uint256) {}
/**
* Get APR of every ILendingProtocol
*
* @return addresses: array of token addresses
* @return aprs: array of aprs (ordered in respect to the `addresses` array)
*/
function getAPRs() external view returns (address[] memory, uint256[] memory) {}
/**
* Get current avg APR of this IdleToken
*
* @return avgApr: current weighted avg apr
*/
function getAvgAPR() public view returns (uint256) {}
/**
* Get how many gov tokens a user is entitled to (this may not include eventual undistributed tokens)
*
* @param _usr : user address
* @return : array of amounts for each gov token
*/
function getGovTokensAmounts(address _usr) external view returns (uint256[] memory _amounts) {}
// external
/**
* Used to mint IdleTokens, given an underlying amount (eg. DAI).
* This method triggers a rebalance of the pools if _skipRebalance is set to false
* NOTE: User should 'approve' _amount of tokens before calling mintIdleToken
* NOTE 2: this method can be paused
* This method use GasTokens of this contract (if present) to get a gas discount
*
* @param _amount : amount of underlying token to be lended
* @param _referral : referral address
* @return mintedTokens : amount of IdleTokens minted
*/
function mintIdleToken(uint256 _amount, bool _skipRebalance, address _referral)
external returns (uint256 mintedTokens) {}
/**
* Here we calc the pool share one can withdraw given the amount of IdleToken they want to burn
*
* @param _amount : amount of IdleTokens to be burned
* @return redeemedTokens : amount of underlying tokens redeemed
*/
function redeemIdleToken(uint256 _amount) external returns (uint256 redeemedTokens) {}
/**
* Here we calc the pool share one can withdraw given the amount of IdleToken they want to burn
* and send interest-bearing tokens (eg. cDAI/iDAI) directly to the user.
* Underlying (eg. DAI) is not redeemed here.
*
* @param _amount : amount of IdleTokens to be burned
*/
function redeemInterestBearingTokens(uint256 _amount) external {}
/**
* Dynamic allocate all the pool across different lending protocols if needed,
* rebalance without params
*
* NOTE: this method can be paused
*
* @return : whether has rebalanced or not
*/
function rebalance() external returns (bool) {}
/**
* Allow any users to set new allocations as long as the new allocation
* gives a better avg APR than before
* Allocations should be in the format [100000, 0, 0, 0, ...] where length is the same
* as lastAllocations variable and the sum of all value should be == 100000
*
* This method is not callble if this instance of IdleToken is a risk adjusted instance
* NOTE: this method can be paused
*
* @param _newAllocations : array with new allocations in percentage
* @return hasRebalanced : whether has rebalanced or not
* @return avgApr : the new avg apr after rebalance
*/
function openRebalance(uint256[] calldata _newAllocations)
external whenNotPaused
returns (bool hasRebalanced, uint256 avgApr) {}
}
| * Allow any users to set new allocations as long as the new allocation gives a better avg APR than before Allocations should be in the format [100000, 0, 0, 0, ...] where length is the same as lastAllocations variable and the sum of all value should be == 100000 This method is not callble if this instance of IdleToken is a risk adjusted instance NOTE: this method can be paused @param _newAllocations : array with new allocations in percentage @return hasRebalanced : whether has rebalanced or not @return avgApr : the new avg apr after rebalance/ | returns (bool hasRebalanced, uint256 avgApr) {}
| 5,433,033 | [
1,
7009,
1281,
3677,
358,
444,
394,
23804,
487,
1525,
487,
326,
394,
13481,
14758,
279,
7844,
11152,
432,
8025,
2353,
1865,
2262,
12352,
1410,
506,
316,
326,
740,
306,
21,
11706,
16,
374,
16,
374,
16,
374,
16,
1372,
65,
1625,
769,
353,
326,
1967,
487,
1142,
8763,
1012,
2190,
471,
326,
2142,
434,
777,
460,
1410,
506,
422,
25259,
1220,
707,
353,
486,
745,
7119,
309,
333,
791,
434,
28156,
1345,
353,
279,
18404,
13940,
791,
5219,
30,
333,
707,
848,
506,
17781,
225,
389,
2704,
8763,
1012,
294,
526,
598,
394,
23804,
316,
11622,
327,
711,
426,
12296,
72,
294,
2856,
711,
283,
12296,
72,
578,
486,
327,
11152,
37,
683,
294,
326,
394,
11152,
513,
86,
1839,
283,
12296,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
1135,
261,
6430,
711,
426,
12296,
72,
16,
2254,
5034,
11152,
37,
683,
13,
2618,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-FileCopyrightText: 2019 Alex Beregszaszi
// SPDX-FileCopyrightText: 2020 Serokell <https://serokell.io/>
//
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
library Blake2b {
uint256 constant public BLOCK_SIZE = 128;
uint256 constant public WORD_SIZE = 32;
// And we rely on the fact that BLOCK_SIZE % WORD_SIZE == 0
// Initialise the state with a given `key` and required `out_len` hash length.
// This is a bit misleadingly called state as it not only includes the Blake2 state,
// but every field needed for the "blake2 f function precompile".
//
// This is a tightly packed buffer of:
// - rounds: 32-bit BE
// - h: 8 x 64-bit LE
// - m: 16 x 64-bit LE
// - t: 2 x 64-bit LE
// - f: 8-bit
function init(uint out_len)
private
pure
returns (bytes memory state)
{
// This is entire state transmitted to the precompile.
// It is byteswapped for the encoding requirements, additionally
// the IV has the initial parameter block 0 XOR constant applied, but
// not the key and output length.
state = hex"0000000c08c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
// TODO: support salt and personalization
}
// This calls the blake2 precompile ("function F of the spec").
// It expects the state was updated with the next block. Upon returning the state will be updated,
// but the supplied block data will not be cleared.
function call_function_f(bytes memory state)
private
view
{
assembly {
let state_ptr := add(state, 32)
if iszero(staticcall(not(0), 0x09, state_ptr, 0xd5, add(state_ptr, 4), 0x40)) {
revert(0, 0)
}
}
}
function update_finalise(bytes memory state, bytes memory data)
private
view
{
// NOTE [input size]
// Technically, this can be 128 bits, but we need to manually convert
// it from big-endian to little-endian, which is boring, so, hopefully,
// 24 bits should be more than enough.
uint input_counter = 0;
require(data.length <= (1 << 24) - 1);
// This is the memory location where the input data resides.
uint inp_ptr;
assembly {
inp_ptr := add(data, 32)
}
// This is the memory location where the "data block" starts for the precompile.
uint msg_ptr;
assembly {
// The `rounds` field is 4 bytes long and the `h` field is 64-bytes long.
// Also the length stored in the bytes data type is 32 bytes.
msg_ptr := add(state, 100)
}
uint remains = data.length;
do {
uint out_ptr = msg_ptr;
// Copy full words first.
while (remains >= WORD_SIZE && out_ptr < msg_ptr + BLOCK_SIZE) {
assembly {
mstore(out_ptr, mload(inp_ptr))
}
inp_ptr += WORD_SIZE;
out_ptr += WORD_SIZE;
remains -= WORD_SIZE;
}
input_counter += out_ptr - msg_ptr;
// Now copy the remaining <32 bytes.
if (remains > 0 && out_ptr < msg_ptr + BLOCK_SIZE) {
uint mask = (1 << (8 * (WORD_SIZE - remains))) - 1;
assembly {
mstore(out_ptr, and(mload(inp_ptr), not(mask)))
}
// inp_ptr += remains; // No need to udpate as we are done here
out_ptr += WORD_SIZE;
input_counter += remains;
remains = 0;
}
// If this block is the last one.
if (remains == 0) {
// Pad.
while (out_ptr < msg_ptr + BLOCK_SIZE) {
assembly {
mstore(out_ptr, 0)
}
out_ptr += WORD_SIZE;
}
// Set the last block indicator.
assembly {
mstore8(add(state, 244), 1)
}
}
// Set length field (little-endian) for maximum of 24-bits.
assembly {
mstore8(add(state, 228), and(input_counter, 0xff))
mstore8(add(state, 229), and(shr(8, input_counter), 0xff))
mstore8(add(state, 230), and(shr(16, input_counter), 0xff))
}
// Call the precompile
call_function_f(state);
} while (remains > 0);
}
// Compute a hash of bytes.
function hash(uint out_len, bytes memory data)
internal
view
returns (bytes memory output)
{
require(out_len > 0 && out_len <= 64);
bytes memory state = init(out_len);
update_finalise(state, data);
output = new bytes(out_len);
// We’ll just treat cases indivifually, because we can.
if (out_len < 32) {
uint mask = (1 << (8 * (WORD_SIZE - out_len))) - 1;
assembly {
let out_ptr := add(output, 32)
let out_word := and(mload(add(state, /*32 + 4 =*/ 36)), not(mask))
let orig_word := and(mload(out_ptr), mask)
mstore(out_ptr, or(out_word, orig_word))
}
} else {
// Copy first word.
assembly {
mstore(add(output, 32), mload(add(state, /*32 + 4 =*/ 36)))
}
if (out_len < 64) {
uint mask = (1 << (8 * (2 * WORD_SIZE - out_len))) - 1;
assembly {
let out_ptr := add(output, /*32 + 32 =*/ 64)
let out_word := and(mload(add(state, /*32 + 4 + 32 =*/ 68)), not(mask))
let orig_word := and(mload(out_ptr), mask)
mstore(out_ptr, or(out_word, orig_word))
}
} else {
assembly {
mstore(add(output, /*32 + 32 =*/ 64), mload(add(state, /*32 + 4 + 32 =*/ 68)))
}
}
}
}
}
| inp_ptr += remains; No need to udpate as we are done here | out_ptr += WORD_SIZE;
| 1,805,554 | [
1,
31647,
67,
6723,
1011,
22632,
31,
282,
2631,
1608,
358,
16673,
340,
487,
732,
854,
2731,
2674,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
7734,
596,
67,
6723,
1011,
21464,
67,
4574,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
// website: www.defyswap.finance
//
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor() internal {}
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
//
/**
* @dev 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 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;
}
}
//
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the bep token owner.
*/
function getOwner() external view returns (address);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address _owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
//
/**
* @dev 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;
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
//
/**
* @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);
}
}
}
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
//
/**
* @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, Ownable {
using SafeMath for uint256;
using Address for address;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) internal _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 bep token owner.
*/
function getOwner() external override view returns (address) {
return owner();
}
/**
* @dev Returns the token name.
*/
function name() public override view returns (string memory) {
return _name;
}
/**
* @dev Returns the token decimals.
*/
function decimals() public override view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the token symbol.
*/
function symbol() public override view returns (string memory) {
return _symbol;
}
/**
* @dev See {ERC20-totalSupply}.
*/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {ERC20-balanceOf}.
*/
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
/**
* @dev See {ERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {ERC20-allowance}.
*/
function allowance(address owner, address spender) public override view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {ERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {ERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public 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 {ERC20-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 {ERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(subtractedValue, 'ERC20: decreased allowance below zero')
);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing
* the total supply.
*
* Requirements
*
* - `msg.sender` must be the token owner
*/
function mint(uint256 amount) public virtual onlyOwner returns (bool) {
_mint(_msgSender(), amount);
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');
_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')
);
}
}
// DFYToken with Governance.
contract DfyToken is ERC20('DefySwap', 'DFY') {
mapping (address => bool) private _isRExcludedFromFee; // excluded list from receive
mapping (address => bool) private _isSExcludedFromFee; // excluded list from send
mapping (address => bool) private _isPair;
uint256 public _burnFee = 40;
uint256 public _ilpFee = 5;
uint256 public _devFee = 4;
uint256 public _maxTxAmount = 10 * 10**6 * 1e18;
uint256 public constant _maxSupply = 10 * 10**6 * 1e18;
address public BURN_VAULT;
address public ILP_VAULT;
address public defyMaster;
address public dev;
address public router;
event NewDeveloper(address);
event ExcludeFromFeeR(address);
event ExcludeFromFeeS(address);
event IncludeInFeeR(address);
event IncludeInFeeS(address);
event SetRouter(address);
event SetPair(address,bool);
event BurnFeeUpdated(uint256,uint256);
event IlpFeeUpdated(uint256,uint256);
event DevFeeUpdated(uint256,uint256);
event SetBurnVault(address);
event SetIlpVault(address);
event SetDefyMaster(address);
event Burn(uint256);
modifier onlyDev() {
require(msg.sender == owner() || msg.sender == dev , "Error: Require developer or Owner");
_;
}
modifier onlyMaster() {
require(msg.sender == defyMaster , "Error: Only DefyMaster");
_;
}
constructor(address _dev, address _bunVault, uint256 _initAmount) public {
require(_dev != address(0), 'DEFY: dev cannot be the zero address');
require(_bunVault != address(0), 'DEFY: burn vault cannot be the zero address');
dev = _dev;
BURN_VAULT = _bunVault;
defyMaster = msg.sender;
mint(msg.sender,_initAmount);
_isRExcludedFromFee[msg.sender] = true;
_isRExcludedFromFee[_bunVault] = true;
_isRExcludedFromFee[_dev] = true;
_isSExcludedFromFee[msg.sender] = true;
_isSExcludedFromFee[_bunVault] = true;
_isSExcludedFromFee[_dev] = true;
}
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (DefyMaster).
function mint(address _to, uint256 _amount) public onlyMaster returns (bool) {
require(_maxSupply >= totalSupply().add(_amount) , "Error : Total Supply Reached" );
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
return true;
}
function mint(uint256 amount) public override onlyMaster returns (bool) {
require(_maxSupply >= totalSupply().add(amount) , "Error : Total Supply Reached" );
_mint(_msgSender(), amount);
_moveDelegates(address(0), _delegates[_msgSender()], amount);
return true;
}
// Exclude an account from receive fee
function excludeFromFeeR(address account) external onlyOwner {
require(!_isRExcludedFromFee[account], "Account is already excluded From receive Fee");
_isRExcludedFromFee[account] = true;
emit ExcludeFromFeeR(account);
}
// Exclude an account from send fee
function excludeFromFeeS(address account) external onlyOwner {
require(!_isSExcludedFromFee[account], "Account is already excluded From send Fee");
_isSExcludedFromFee[account] = true;
emit ExcludeFromFeeS(account);
}
// Include an account in receive fee
function includeInFeeR(address account) external onlyOwner {
require( _isRExcludedFromFee[account], "Account is not excluded From receive Fee");
_isRExcludedFromFee[account] = false;
emit IncludeInFeeR(account);
}
// Include an account in send fee
function includeInFeeS(address account) external onlyOwner {
require( _isSExcludedFromFee[account], "Account is not excluded From send Fee");
_isSExcludedFromFee[account] = false;
emit IncludeInFeeS(account);
}
function setRouter(address _router) external onlyOwner {
require(_router != address(0), 'DEFY: Router cannot be the zero address');
router = _router;
emit SetRouter(_router);
}
function setPair(address _pair, bool _status) external onlyOwner {
require(_pair != address(0), 'DEFY: Pair cannot be the zero address');
_isPair[_pair] = _status;
emit SetPair(_pair , _status);
}
function setBurnFee(uint256 burnFee) external onlyOwner() {
require(burnFee <= 80 , "Error : MaxBurnFee is 8%");
uint256 _previousBurnFee = _burnFee;
_burnFee = burnFee;
emit BurnFeeUpdated(_previousBurnFee,_burnFee);
}
function setDevFee(uint256 devFee) external onlyOwner() {
require(devFee <= 20 , "Error : MaxDevFee is 2%");
uint256 _previousDevFee = _devFee;
_devFee = devFee;
emit DevFeeUpdated(_previousDevFee,_devFee);
}
function setIlpFee(uint256 ilpFee) external onlyOwner() {
require(ilpFee <= 50 , "Error : MaxIlpFee is 5%");
uint256 _previousIlpFee = _ilpFee;
_ilpFee = ilpFee;
emit IlpFeeUpdated(_previousIlpFee,_ilpFee);
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
require(maxTxPercent >= 5 , "Error : Minimum maxTxLimit is 5%");
require(maxTxPercent <= 100 , "Error : Maximum maxTxLimit is 100%");
_maxTxAmount = totalSupply().mul(maxTxPercent).div(
10**2
);
}
function setDev(address _dev) external onlyDev {
require(dev != address(0), 'DEFY: dev cannot be the zero address');
_isRExcludedFromFee[dev] = false;
_isSExcludedFromFee[dev] = false;
dev = _dev ;
_isRExcludedFromFee[_dev] = true;
_isSExcludedFromFee[_dev] = true;
emit NewDeveloper(_dev);
}
function setBurnVault(address _burnVault) external onlyMaster {
_isRExcludedFromFee[BURN_VAULT] = false;
_isSExcludedFromFee[BURN_VAULT] = false;
BURN_VAULT = _burnVault ;
_isRExcludedFromFee[_burnVault] = true;
_isSExcludedFromFee[_burnVault] = true;
emit SetBurnVault(_burnVault);
}
function setIlpVault(address _ilpVault) external onlyOwner {
_isRExcludedFromFee[ILP_VAULT] = false;
_isSExcludedFromFee[ILP_VAULT] = false;
ILP_VAULT = _ilpVault;
_isRExcludedFromFee[_ilpVault] = true;
_isSExcludedFromFee[_ilpVault] = true;
emit SetIlpVault(_ilpVault);
}
function setMaster(address master) public onlyMaster {
require(master!= address(0), 'DEFY: DefyMaster cannot be the zero address');
defyMaster = master;
_isRExcludedFromFee[master] = true;
_isSExcludedFromFee[master] = true;
emit SetDefyMaster(master);
}
function isExcludedFromFee(address account) external view returns(bool Rfee , bool SFee) {
return (_isRExcludedFromFee[account] , _isSExcludedFromFee[account] );
}
function isPair(address account) external view returns(bool) {
return _isPair[account];
}
function burnToVault(uint256 amount) public {
_transfer(msg.sender, BURN_VAULT, amount);
}
// @notice Destroys `amount` tokens from `account`, reducing the total supply.
function burn(uint256 amount) public {
_burn(msg.sender, amount);
_moveDelegates(address(0), _delegates[msg.sender], amount);
emit Burn(amount);
}
function transferTaxFree(address recipient, uint256 amount) public returns (bool) {
require(_isPair[_msgSender()] || _msgSender() == router , "DFY: Only DefySwap Router or Defy pair");
super._transfer(_msgSender(), recipient, amount);
return true;
}
function transferFromTaxFree(address sender, address recipient, uint256 amount) public returns (bool) {
require(_isPair[_msgSender()] || _msgSender() == router , "DFY: Only DefySwap Router or Defy pair");
super._transfer(sender, recipient, amount);
super._approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(amount, 'ERC20: transfer amount exceeds allowance')
);
return true;
}
/// @dev overrides transfer function to meet tokenomics of DEFY
function _transfer(address sender, address recipient, uint256 amount) internal override {
//if any account belongs to _isExcludedFromFee account then remove the fee
if (_isSExcludedFromFee[sender] || _isRExcludedFromFee[recipient]) {
super._transfer(sender, recipient, amount);
}
else {
// A percentage of every transfer goes to Burn Vault ,ILP Vault & Dev
uint256 burnAmount = amount.mul(_burnFee).div(1000);
uint256 ilpAmount = amount.mul(_ilpFee).div(1000);
uint256 devAmount = amount.mul(_devFee).div(1000);
// Remainder of transfer sent to recipient
uint256 sendAmount = amount.sub(burnAmount).sub(ilpAmount).sub(devAmount);
require(amount == sendAmount + burnAmount + ilpAmount + devAmount , "DEFY Transfer: Fee value invalid");
super._transfer(sender, BURN_VAULT, burnAmount);
super._transfer(sender, ILP_VAULT, ilpAmount);
super._transfer(sender, dev, devAmount);
super._transfer(sender, recipient, sendAmount);
amount = sendAmount;
}
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @dev 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;
/// @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), "DEFY::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "DEFY::delegateBySig: invalid nonce");
require(now <= expiry, "DEFY::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, "DEFY::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 = balanceOf(delegator); // balance of underlying DEFYs (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, "DEFY::_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;
}
}
//
/**
* @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');
}
}
}
// DefySTUB interface.
interface DefySTUB is IERC20 {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (DefyMaster).
function mint(address _to, uint256 _amount) external ;
function burn(address _from ,uint256 _amount) external ;
}
//BurnVault
contract BurnVault is Ownable {
DfyToken public defy;
address public defyMaster;
event SetDefyMaster(address);
event Burn(uint256);
modifier onlyDefy() {
require(msg.sender == owner() || msg.sender == defyMaster , "Error: Require developer or Owner");
_;
}
function setDefyMaster (address master) external onlyDefy{
defyMaster = master ;
emit SetDefyMaster(master);
}
function setDefy (address _defy) external onlyDefy{
defy = DfyToken(_defy);
}
function burn () public onlyDefy {
uint256 amount = defy.balanceOf(address(this));
defy.burn(amount);
emit Burn(amount);
}
function burnPortion (uint256 amount) public onlyDefy {
defy.burn(amount);
emit Burn(amount);
}
}
//ILP Interface.
interface ImpermanentLossProtection{
//IMPERMANENT LOSS PROTECTION ABI
function add(address _lpToken, IERC20 _token0, IERC20 _token1, bool _offerILP) external;
function set(uint256 _pid, IERC20 _token0,IERC20 _token1, bool _offerILP) external;
function getDepositValue(uint256 amount, uint256 _pid) external view returns (uint256 userDepValue);
function defyTransfer(address _to, uint256 _amount) external;
function getDefyPrice(uint256 _pid) external view returns (uint256 defyPrice);
}
// DefyMaster is the master of Defy. He can make Dfy and he is a fair guy.
// Have fun reading it. Hopefully it's bug-free. God bless.
contract DefyMaster is Ownable , ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below. (same as rewardDebt)
uint256 rewardDebtDR; // Reward debt Secondary reward. See explanation below.
uint256 depositTime; // Time when the user deposit LP tokens.
uint256 depVal; // LP token value at the deposit time.
//
// We do some fancy math here. Basically, any point in time, the amount of DFYs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accDefyPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accDefyPerShare` (and `lastRewardTimestamp`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
DefySTUB stubToken; // STUB / Receipt Token for farmers.
uint256 allocPoint; // How many allocation points assigned to this pool. DFYs to distribute per Second.
uint256 allocPointDR; // How many allocation points assigned to this pool for Secondary Reward.
uint256 depositFee; // LP Deposit fee.
uint256 withdrawalFee; // LP Withdrawal fee
uint256 lastRewardTimestamp; // Last timestamp that DFYs distribution occurs.
uint256 lastRewardTimestampDR; // Last timestamp that Secondary Reward distribution occurs.
uint256 rewardEndTimestamp; // Reward ending Timestamp.
uint256 accDefyPerShare; // Accumulated DFYs per share, times 1e12. See below.
uint256 accSecondRPerShare; // Accumulated Second Reward Tokens per share, times 1e24. See below.
uint256 lpSupply; // Total Lp tokens Staked in farm.
bool impermanentLossProtection; // ILP availability
bool issueStub; // STUB Availability.
}
// The DFY TOKEN!
DfyToken public defy;
// Secondary Reward Token.
IERC20 public secondR;
// BurnVault.
BurnVault public burn_vault;
//ILP Contract
ImpermanentLossProtection public ilp;
// Dev address.
address public devaddr;
// Emergency Dev
address public emDev;
// Deposit/Withdrawal Fee address
address public feeAddress;
// DFY tokens created per second.
uint256 public defyPerSec;
// Secondary Reward distributed per second.
uint256 public secondRPerSec;
// Bonus muliplier for early dfy makers.
uint256 public BONUS_MULTIPLIER = 1;
//Max uint256
uint256 constant MAX_INT = type(uint256).max ;
// Seconds per burn cycle.
uint256 public SECONDS_PER_CYCLE = 365 * 2 days ;
// Max DFY Supply.
uint256 public constant MAX_SUPPLY = 10 * 10**6 * 1e18;
// Next minting cycle start timestamp.
uint256 public nextCycleTimestamp;
// The Timestamp when Secondary Reward mining ends.
uint256 public endTimestampDR = MAX_INT;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// Total allocation points for Dual Reward. Must be the sum of all Dual reward allocation points in all pools.
uint256 public totalAllocPointDR = 0;
// The Timestamp when DFY mining starts.
uint256 public startTimestamp;
modifier onlyDev() {
require(msg.sender == owner() || msg.sender == devaddr , "Error: Require developer or Owner");
_;
}
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event SetFeeAddress(address newAddress);
event SetDevAddress(address newAddress);
event SetDFY(address dfy);
event SetSecondaryReward(address newToken);
event UpdateEmissionRate(uint256 defyPerSec);
event UpdateSecondaryEmissionRate(uint256 secondRPerSec);
event DFYOwnershipTransfer(address newOwner);
event RenounceEmDev();
event addPool(
uint256 indexed pid,
address lpToken,
uint256 allocPoint,
uint256 allocPointDR,
uint256 depositFee,
uint256 withdrawalFee,
bool offerILP,
bool issueStub,
uint256 rewardEndTimestamp);
event setPool(
uint256 indexed pid,
uint256 allocPoint,
uint256 allocPointDR,
uint256 depositFee,
uint256 withdrawalFee,
bool offerILP,
bool issueStub,
uint256 rewardEndTimestamp);
event UpdateStartTimestamp(uint256 newStartTimestamp);
constructor(
DfyToken _defy,
DefySTUB _stub,
BurnVault _burnvault,
address _devaddr,
address _emDev,
address _feeAddress,
uint256 _startTimestamp,
uint256 _initMint
) public {
require(_devaddr != address(0), 'DEFY: dev cannot be the zero address');
require(_feeAddress != address(0), 'DEFY: FeeAddress cannot be the zero address');
require(_startTimestamp >= block.timestamp , 'DEFY: Invalid start time');
defy = _defy;
burn_vault = _burnvault;
devaddr = _devaddr;
emDev = _emDev;
feeAddress = _feeAddress;
startTimestamp = _startTimestamp;
defyPerSec = (MAX_SUPPLY.sub(_initMint)).div(SECONDS_PER_CYCLE);
nextCycleTimestamp = startTimestamp.add(SECONDS_PER_CYCLE);
// staking pool
poolInfo.push(PoolInfo({
lpToken: _defy,
stubToken: _stub,
allocPoint: 400,
allocPointDR: 0,
depositFee: 0,
withdrawalFee: 0,
lastRewardTimestamp: startTimestamp,
lastRewardTimestampDR: startTimestamp,
rewardEndTimestamp: MAX_INT,
accDefyPerShare: 0,
accSecondRPerShare: 0,
lpSupply: 0,
impermanentLossProtection: false,
issueStub: true
}));
totalAllocPoint = 400;
}
function setImpermanentLossProtection(address _ilp)public onlyDev returns (bool){
require(_ilp != address(0), 'DEFY: ILP cannot be the zero address');
ilp = ImpermanentLossProtection(_ilp);
}
function setFeeAddress(address _feeAddress)public onlyDev returns (bool){
require(_feeAddress != address(0), 'DEFY: FeeAddress cannot be the zero address');
feeAddress = _feeAddress;
emit SetFeeAddress(_feeAddress);
return true;
}
function setDFY(DfyToken _dfy)public onlyDev returns (bool){
require(_dfy != DfyToken(0), 'DEFY: DFY cannot be the zero address');
defy = _dfy;
emit SetDFY(address(_dfy));
return true;
}
function setSecondaryReward(IERC20 _rewardToken)public onlyDev returns (bool){
require(_rewardToken != IERC20(0), 'DEFY: SecondaryReward cannot be the zero address');
secondR = _rewardToken;
emit SetSecondaryReward(address(_rewardToken));
return true;
}
function getUserInfo(uint256 pid, address userAddr)
public
view
returns(uint256 deposit, uint256 rewardDebt, uint256 rewardDebtDR, uint256 daysSinceDeposit, uint256 depVal)
{
UserInfo storage user = userInfo[pid][userAddr];
return (user.amount, user.rewardDebt, user.rewardDebtDR, _getDaysSinceDeposit(pid, userAddr), user.depVal);
}
//Time Functions
function getDaysSinceDeposit(uint256 pid, address userAddr)
external
view
returns (uint256 daysSinceDeposit)
{
return _getDaysSinceDeposit(pid, userAddr);
}
function _getDaysSinceDeposit(uint256 _pid, address _userAddr)
internal
view
returns (uint256)
{
UserInfo storage user = userInfo[_pid][_userAddr];
if (block.timestamp < user.depositTime){
return 0;
}else{
return (block.timestamp.sub(user.depositTime)) / 1 days;
}
}
function checkForIL(uint256 pid, address userAddr)
external
view
returns (uint256 extraDefy)
{
UserInfo storage user = userInfo[pid][userAddr];
return _checkForIL(pid, user);
}
function _checkForIL(uint256 _pid, UserInfo storage user)
internal
view
returns (uint256)
{
uint256 defyPrice = ilp.getDefyPrice(_pid);
uint256 currentVal = ilp.getDepositValue(user.amount, _pid);
if(currentVal < user.depVal){
uint256 difference = user.depVal.sub(currentVal);
return difference.div(defyPrice);
}else return 0;
}
function setStartTimestamp(uint256 sTimestamp) public onlyDev{
require(sTimestamp > block.timestamp, "Invalid Timestamp");
startTimestamp = sTimestamp;
emit UpdateStartTimestamp(sTimestamp);
}
function updateMultiplier(uint256 multiplierNumber) public onlyDev {
require(multiplierNumber != 0, " multiplierNumber should not be null");
BONUS_MULTIPLIER = multiplierNumber;
}
function updateEmissionRate(uint256 endTimestamp) external {
require(endTimestamp > ((block.timestamp).add(182 days)), "Minimum duration is 6 months");
require ( msg.sender == devaddr , "only dev!");
massUpdatePools();
SECONDS_PER_CYCLE = endTimestamp.sub(block.timestamp);
defyPerSec = MAX_SUPPLY.sub(defy.totalSupply()).div(SECONDS_PER_CYCLE);
nextCycleTimestamp = endTimestamp;
emit UpdateEmissionRate(defyPerSec);
}
function updateReward() internal {
uint256 burnAmount = defy.balanceOf(address(burn_vault));
defyPerSec = burnAmount.div(SECONDS_PER_CYCLE);
burn_vault.burn();
emit UpdateEmissionRate(defyPerSec);
}
function updateSecondReward(uint256 _reward, uint256 _endTimestamp) public onlyOwner{
require(_endTimestamp > block.timestamp , "invalid End timestamp");
massUpdatePools();
endTimestampDR = _endTimestamp;
secondRPerSec = 0;
massUpdatePools();
secondRPerSec = _reward.div((_endTimestamp).sub(block.timestamp));
emit UpdateSecondaryEmissionRate(secondRPerSec);
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
// XXX DO NOT set ILP for non DFY pairs.
function add(
uint256 _allocPoint,
uint256 _allocPointDR,
IERC20 _lpToken,
DefySTUB _stub,
IERC20 _token0,
IERC20 _token1,
uint256 _depositFee,
uint256 _withdrawalFee,
bool _offerILP,
bool _issueSTUB,
uint256 _rewardEndTimestamp
) public onlyDev {
require(_depositFee <= 600, "Add : Max Deposit Fee is 6%");
require(_withdrawalFee <= 600, "Add : Max Deposit Fee is 6%");
require(_rewardEndTimestamp > block.timestamp , "Add: invalid rewardEndTimestamp");
massUpdatePools();
ilp.add(address(_lpToken), _token0, _token1, _offerILP);
uint256 lastRewardTimestamp = block.timestamp > startTimestamp ? block.timestamp : startTimestamp;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
totalAllocPointDR = totalAllocPointDR.add(_allocPointDR);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
stubToken: _stub,
allocPoint: _allocPoint,
allocPointDR: _allocPointDR,
depositFee: _depositFee,
withdrawalFee: _withdrawalFee,
lastRewardTimestamp: lastRewardTimestamp,
lastRewardTimestampDR: lastRewardTimestamp,
rewardEndTimestamp: _rewardEndTimestamp,
accDefyPerShare: 0,
accSecondRPerShare: 0,
lpSupply: 0,
impermanentLossProtection: _offerILP,
issueStub: _issueSTUB
}));
emit addPool(poolInfo.length - 1, address(_lpToken), _allocPoint, _allocPointDR, _depositFee, _withdrawalFee, _offerILP, _issueSTUB, _rewardEndTimestamp);
}
// Update the given pool's DFY allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
uint256 _allocPointDR,
IERC20 _token0,
IERC20 _token1,
uint256 _depositFee,
uint256 _withdrawalFee,
bool _offerILP,
bool _issueSTUB,
uint256 _rewardEndTimestamp
) public onlyOwner {
require(_depositFee <= 600, "Add : Max Deposit Fee is 6%");
require(_withdrawalFee <= 600, "Add : Max Deposit Fee is 6%");
require(_rewardEndTimestamp > block.timestamp , "Add: invalid rewardEndTimestamp");
massUpdatePools();
ilp.set(_pid, _token0, _token1, _offerILP);
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
totalAllocPointDR = totalAllocPointDR.sub(poolInfo[_pid].allocPointDR).add(_allocPointDR);
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].allocPointDR = _allocPointDR;
poolInfo[_pid].depositFee = _depositFee;
poolInfo[_pid].withdrawalFee = _withdrawalFee;
poolInfo[_pid].rewardEndTimestamp = _rewardEndTimestamp;
poolInfo[_pid].impermanentLossProtection = _offerILP;
poolInfo[_pid].issueStub = _issueSTUB;
emit setPool(_pid , _allocPoint, _allocPointDR, _depositFee, _withdrawalFee, _offerILP, _issueSTUB, _rewardEndTimestamp);
}
// Return reward multiplier over the given _from to _to Timestamp.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
}
// View function to see pending DFYs on frontend.
function pendingDefy(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accDefyPerShare = pool.accDefyPerShare;
uint256 lpSupply = pool.lpSupply;
if (block.timestamp > pool.lastRewardTimestamp && lpSupply != 0 && totalAllocPoint != 0) {
uint256 blockTimestamp;
if(block.timestamp < nextCycleTimestamp){
blockTimestamp = block.timestamp < pool.rewardEndTimestamp ? block.timestamp : pool.rewardEndTimestamp;
}
else{
blockTimestamp = nextCycleTimestamp;
}
uint256 multiplier = getMultiplier(pool.lastRewardTimestamp, blockTimestamp);
uint256 defyReward = multiplier.mul(defyPerSec).mul(pool.allocPoint).div(totalAllocPoint);
accDefyPerShare = accDefyPerShare.add(defyReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accDefyPerShare).div(1e12).sub(user.rewardDebt);
}
// View function to see pending Secondary Reward on frontend.
function pendingSecondR(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSecondRPerShare = pool.accSecondRPerShare;
uint256 lpSupply = pool.lpSupply;
if (block.timestamp > pool.lastRewardTimestampDR && lpSupply != 0 && totalAllocPointDR != 0) {
uint256 blockTimestamp;
if(block.timestamp < endTimestampDR){
blockTimestamp = block.timestamp < pool.rewardEndTimestamp ? block.timestamp : pool.rewardEndTimestamp;
}
else{
blockTimestamp = endTimestampDR;
}
uint256 multiplier = getMultiplier(pool.lastRewardTimestampDR, blockTimestamp);
uint256 secondRReward = multiplier.mul(secondRPerSec).mul(pool.allocPointDR).div(totalAllocPointDR);
accSecondRPerShare = accSecondRPerShare.add(secondRReward.mul(1e24).div(lpSupply));
}
return user.amount.mul(accSecondRPerShare).div(1e24).sub(user.rewardDebtDR);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
if (block.timestamp > nextCycleTimestamp){
nextCycleTimestamp = (block.timestamp).add(SECONDS_PER_CYCLE);
defyPerSec = 0;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
updateReward();
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePoolPb(uint256 _pid) public {
if (block.timestamp > nextCycleTimestamp){
massUpdatePools();
}
else {
updatePool(_pid);
}
}
function updatePool(uint256 _pid) internal {
PoolInfo storage pool = poolInfo[_pid];
if (block.timestamp <= pool.lastRewardTimestamp && block.timestamp <= pool.lastRewardTimestampDR) {
return;
}
uint256 lpSupply = pool.lpSupply;
uint256 blockTimestamp;
if(block.timestamp < nextCycleTimestamp){
blockTimestamp = block.timestamp < pool.rewardEndTimestamp ? block.timestamp : pool.rewardEndTimestamp;
}
else{
blockTimestamp = nextCycleTimestamp;
}
uint256 blockTimestampDR;
if(block.timestamp < endTimestampDR){
blockTimestampDR = block.timestamp < pool.rewardEndTimestamp ? block.timestamp : pool.rewardEndTimestamp;
}
else{
blockTimestampDR = endTimestampDR;
}
if (lpSupply == 0) {
pool.lastRewardTimestamp = blockTimestamp;
pool.lastRewardTimestampDR = blockTimestampDR;
return;
}
if (pool.allocPoint == 0 && pool.allocPointDR == 0) {
pool.lastRewardTimestamp = blockTimestamp;
pool.lastRewardTimestampDR = blockTimestampDR;
return;
}
uint256 defyReward = 0 ;
uint256 secondRReward = 0 ;
if(totalAllocPoint != 0){
uint256 multiplier = getMultiplier(pool.lastRewardTimestamp, blockTimestamp);
defyReward = multiplier.mul(defyPerSec).mul(pool.allocPoint).div(totalAllocPoint);
}
if(totalAllocPointDR != 0){
uint256 multiplier = getMultiplier(pool.lastRewardTimestampDR, blockTimestampDR);
secondRReward = multiplier.mul(secondRPerSec).mul(pool.allocPointDR).div(totalAllocPointDR);
}
if(defyReward > 0 ){
defy.mint(address(this), defyReward);
}
pool.accDefyPerShare = pool.accDefyPerShare.add(defyReward.mul(1e12).div(lpSupply));
pool.accSecondRPerShare = pool.accSecondRPerShare.add(secondRReward.mul(1e24).div(lpSupply));
pool.lastRewardTimestamp = blockTimestamp;
pool.lastRewardTimestampDR = blockTimestampDR;
}
// Deposit LP tokens to DefyMaster for DFY allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePoolPb(_pid);
uint256 amount_ = _amount;
//If the LP token balance is lower than _amount,
//total LP tokens in the wallet will be deposited
if(amount_ > pool.lpToken.balanceOf(msg.sender)){
amount_ = pool.lpToken.balanceOf(msg.sender);
}
//check for ILP DFY
uint256 extraDefy = 0;
if(pool.impermanentLossProtection && user.amount > 0 && _getDaysSinceDeposit(_pid, msg.sender) >= 30){
extraDefy = _checkForIL(_pid, user);
}
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accDefyPerShare).div(1e12).sub(user.rewardDebt);
uint256 pendingDR = user.amount.mul(pool.accSecondRPerShare).div(1e24).sub(user.rewardDebtDR);
if(pending > 0) {
safeDefyTransfer(msg.sender, pending);
}
if(pendingDR > 0) {
safeSecondRTransfer(msg.sender, pendingDR);
}
if(extraDefy > 0 && extraDefy > pending){
ilp.defyTransfer(msg.sender, extraDefy.sub(pending));
}
}
if (amount_ > 0) {
uint256 before = pool.lpToken.balanceOf(address(this));
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), amount_);
uint256 _after = pool.lpToken.balanceOf(address(this));
amount_ = _after.sub(before); // Real amount of LP transfer to this address
if (pool.depositFee > 0) {
uint256 depositFee = amount_.mul(pool.depositFee).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
if (pool.issueStub){
pool.stubToken.mint(msg.sender, amount_.sub(depositFee));
}
user.amount = user.amount.add(amount_).sub(depositFee);
pool.lpSupply = pool.lpSupply.add(amount_).sub(depositFee);
} else {
user.amount = user.amount.add(amount_);
pool.lpSupply = pool.lpSupply.add(amount_);
if (pool.issueStub){
pool.stubToken.mint(msg.sender, amount_);
}
}
}
user.depVal = ilp.getDepositValue(user.amount, _pid);
user.depositTime = block.timestamp;
user.rewardDebt = user.amount.mul(pool.accDefyPerShare).div(1e12);
user.rewardDebtDR = user.amount.mul(pool.accSecondRPerShare).div(1e24);
emit Deposit(msg.sender, _pid, amount_);
}
// Withdraw LP tokens from DefyMaster.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount > 0 , "withdraw: nothing to withdraw");
updatePoolPb(_pid);
uint256 amount_ = _amount;
//If the User LP token balance in farm is lower than _amount,
//total User LP tokens in the farm will be withdrawn
if(amount_ > user.amount){
amount_ = user.amount;
}
//ILP
uint256 extraDefy = 0;
if(pool.impermanentLossProtection && user.amount > 0 && _getDaysSinceDeposit(_pid, msg.sender) >= 30){
extraDefy = _checkForIL(_pid, user);
}
uint256 pending = user.amount.mul(pool.accDefyPerShare).div(1e12).sub(user.rewardDebt);
uint256 pendingDR = user.amount.mul(pool.accSecondRPerShare).div(1e24).sub(user.rewardDebtDR);
if(pending > 0) {
safeDefyTransfer(msg.sender, pending);
}
if(pendingDR > 0) {
safeSecondRTransfer(msg.sender, pendingDR);
}
if(extraDefy > 0 && extraDefy > pending){
ilp.defyTransfer(msg.sender, extraDefy.sub(pending));
}
if(amount_ > 0) {
if (pool.issueStub){
require(pool.stubToken.balanceOf(msg.sender) >= amount_ , "withdraw : No enough STUB tokens!");
pool.stubToken.burn(msg.sender, amount_);
}
if (pool.withdrawalFee > 0) {
uint256 withdrawalFee = amount_.mul(pool.withdrawalFee).div(10000);
pool.lpToken.safeTransfer(feeAddress, withdrawalFee);
pool.lpToken.safeTransfer(address(msg.sender), amount_.sub(withdrawalFee));
} else {
pool.lpToken.safeTransfer(address(msg.sender), amount_);
}
user.amount = user.amount.sub(amount_);
pool.lpSupply = pool.lpSupply.sub(amount_);
}
user.depVal = ilp.getDepositValue(user.amount, _pid);
user.depositTime = block.timestamp;
user.rewardDebt = user.amount.mul(pool.accDefyPerShare).div(1e12);
user.rewardDebtDR = user.amount.mul(pool.accSecondRPerShare).div(1e24);
emit Withdraw(msg.sender, _pid, amount_);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
pool.lpSupply = pool.lpSupply.sub(user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
user.rewardDebtDR = 0;
}
// Safe defy transfer function, just in case if rounding error causes pool to not have enough DFYs.
function safeDefyTransfer(address _to, uint256 _amount) internal {
uint256 defyBal = defy.balanceOf(address(this));
bool successfulTansfer = false;
if (_amount > defyBal) {
successfulTansfer = defy.transfer(_to, defyBal);
} else {
successfulTansfer = defy.transfer(_to, _amount);
}
require(successfulTansfer, "safeDefyTransfer: transfer failed");
}
// Safe SecondR transfer function, just in case if rounding error causes pool to not have enough Secondary reward tokens.
function safeSecondRTransfer(address _to, uint256 _amount) internal {
uint256 secondRBal = secondR.balanceOf(address(this));
bool successfulTansfer = false;
if (_amount > secondRBal) {
successfulTansfer = secondR.transfer(_to, secondRBal);
} else {
successfulTansfer = secondR.transfer(_to, _amount);
}
require(successfulTansfer, "safeSecondRTransfer: transfer failed");
}
// only in an Emergency by emDev
function transferOwnerDfy(address _newOwner) external {
require (msg.sender == emDev , "only emergency dev");
defy.transferOwnership(_newOwner);
emit DFYOwnershipTransfer(_newOwner);
}
function renounceEmDev() external {
require (msg.sender == emDev , "only emergency dev");
emDev = address(0);
emit RenounceEmDev();
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(_devaddr != address(0), 'DEFY: dev cannot be the zero address');
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | Update dev address by the previous dev. | function dev(address _devaddr) public {
require(_devaddr != address(0), 'DEFY: dev cannot be the zero address');
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
| 7,244,301 | [
1,
1891,
4461,
1758,
635,
326,
2416,
4461,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
4461,
12,
2867,
389,
5206,
4793,
13,
1071,
288,
203,
3639,
2583,
24899,
5206,
4793,
480,
1758,
12,
20,
3631,
296,
12904,
61,
30,
4461,
2780,
506,
326,
3634,
1758,
8284,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
4461,
4793,
16,
315,
5206,
30,
341,
322,
7225,
1769,
203,
3639,
4461,
4793,
273,
389,
5206,
4793,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.5.8;
library ECVerify {
function ecverify(bytes32 hash, bytes memory signature) internal pure returns (address signature_address) {
require(signature.length == 65);
bytes32 r;
bytes32 s;
uint8 v;
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
// Here we are loading the last 32 bytes, including 31 bytes of 's'.
v := byte(0, mload(add(signature, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible
if (v < 27) {
v += 27;
}
require(v == 27 || v == 28);
signature_address = ecrecover(hash, v, r, s);
// ecrecover returns zero on error
require(signature_address != address(0x0));
return signature_address;
}
}
pragma solidity 0.5.8;
import './ERC20Basic.sol';
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity 0.5.8;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
pragma solidity 0.5.8;
contract Migrations {
address public owner;
uint public last_completed_migration;
modifier restricted() {
if (msg.sender == owner) _;
}
constructor() public {
owner = msg.sender;
}
function setCompleted(uint completed) public restricted {
last_completed_migration = completed;
}
function upgrade(address new_address) public restricted {
Migrations upgraded = Migrations(new_address);
upgraded.setCompleted(last_completed_migration);
}
}
pragma solidity 0.5.8;
contract MultiOwners {
event AccessGrant(address indexed owner);
event AccessRevoke(address indexed owner);
mapping(address => bool) owners;
constructor() public {
owners[msg.sender] = true;
}
modifier onlyOwner() {
require(owners[msg.sender] == true);
_;
}
function isOwner() view public returns (bool) {
return owners[msg.sender] ? true : false;
}
function checkOwner(address maybe_owner) view public returns (bool) {
return owners[maybe_owner] ? true : false;
}
function grant(address _owner) public onlyOwner {
owners[_owner] = true;
emit AccessGrant(_owner);
}
function revoke(address _owner) public onlyOwner {
require(msg.sender != _owner);
owners[_owner] = false;
emit AccessRevoke(_owner);
}
}
pragma solidity 0.5.8;
import './ERC20.sol';
import './ECVerify.sol';
import './SafeMath64.sol';
/// @title Privatix Service Contract.
contract PrivatixServiceContract {
using SafeMath64 for uint64;
/*
* Data structures
*/
// Number of blocks Agent must wait from last popupServiceOffering or from registerServiceOffering before
// he can popupServiceOffering.
uint32 public popup_period;
// Number of blocks to wait from an uncooperativeClose initiated by the Client
// in order to give the Agent a chance to respond with a balance proof
// in case the sender cheats. After the remove period, the sender can settle
// and delete the channel.
uint32 public challenge_period;
// Number of blocks Agent will wait from registerServiceOffering or from last popupServiceOffering before
// he can delete service offering and receive Agent's deposit back.
uint32 public remove_period;
// Fee that goes to network_fee_address from each closed channel balance.
uint32 public network_fee;
// Address where network_fee is transferred.
address public network_fee_address;
// We temporarily limit total token deposits in a channel to 300 PRIX.
// This is just for the bug bounty release, as a safety measure.
uint64 public constant channel_deposit_bugbounty_limit = 10 ** 8 * 300;
ERC20 public token;
mapping (bytes32 => Channel) private channels;
mapping (bytes32 => ClosingRequest) private closing_requests;
mapping (address => uint64) private internal_balances;
mapping(bytes32 => ServiceOffering) private service_offering_s;
// 52 bytes
struct ServiceOffering{
uint64 min_deposit; // bytes8 - Minimum deposit that Client should place to open state channel.
address agent_address; //bytes20 - Address of Agent.
uint16 max_supply; // bytes2 - Maximum supply of services according to service offerings.
uint16 current_supply; // bytes2 - Currently remaining available supply.
// bytes4 - Last block number when service offering was created, popped-up or channel opened.
// If 0 - offering was removed.
uint32 update_block_number;
}
// 28 bytes
struct Channel {
// uint64 is the maximum uint size needed for deposit based on a
// log2(10^8 * 1275455 token totalSupply) = 46.85.
uint64 deposit;
// Block number at which the channel was opened. Used in creating
// a unique identifier for the channel between a sender and receiver.
// Supports creation of multiple channels between the 2 parties and prevents
// replay of messages in later channels.
uint32 open_block_number;
}
// 28 bytes
struct ClosingRequest {
// Number of tokens owed by the Client when closing the channel.
uint64 closing_balance;
// Block number at which the remove period ends, in case it has been initiated.
uint32 settle_block_number;
}
/*
* Events
*/
event LogChannelCreated(
address indexed _agent,
address indexed _client,
bytes32 indexed _offering_hash,
uint64 _deposit);
event LogChannelToppedUp(
address indexed _agent,
address indexed _client,
bytes32 indexed _offering_hash,
uint32 _open_block_number,
uint64 _added_deposit);
event LogChannelCloseRequested(
address indexed _agent,
address indexed _client,
bytes32 indexed _offering_hash,
uint32 _open_block_number,
uint64 _balance);
event LogOfferingCreated(
address indexed _agent,
bytes32 indexed _offering_hash,
uint64 indexed _min_deposit,
uint16 _current_supply,
uint8 _source_type,
string _source);
event LogOfferingDeleted(
address indexed _agent,
bytes32 indexed _offering_hash);
event LogOfferingPopedUp(
address indexed _agent,
bytes32 indexed _offering_hash,
uint64 indexed _min_deposit,
uint16 _current_supply,
uint8 _source_type,
string _source);
event LogCooperativeChannelClose(
address indexed _agent,
address indexed _client,
bytes32 indexed _offering_hash,
uint32 _open_block_number,
uint64 _balance);
event LogUnCooperativeChannelClose(
address indexed _agent,
address indexed _client,
bytes32 indexed _offering_hash,
uint32 _open_block_number,
uint64 _balance);
/*
* Modifiers
*/
/*
* Constructor
*/
/// @notice Constructor for creating the Privatix Service Contract.
/// @param _token_address The address of the PTC (Privatix Token Contract)
/// @param _popup_period A fixed number of blocks representing the pop-up period.
/// @param _remove_period A fixed number of blocks representing the remove period.
/// @param _challenge_period A fixed number of blocks representing the challenge period.
/// We enforce a minimum of 500 blocks waiting period.
/// after a sender requests the closing of the channel without the receiver's signature.
constructor(
address _token_address,
address _network_fee_address,
uint32 _popup_period,
uint32 _remove_period,
uint32 _challenge_period
) public {
require(_token_address != address(0x0));
require(addressHasCode(_token_address));
require(_network_fee_address != address(0x0));
require(_remove_period >= 100);
require(_popup_period >= 500);
require(_challenge_period >= 5000);
token = ERC20(_token_address);
// Check if the contract is indeed a token contract
require(token.totalSupply() > 0);
network_fee_address = _network_fee_address;
popup_period = _popup_period;
remove_period = _remove_period;
challenge_period = _challenge_period;
}
/*
* External functions
*/
/// @notice Creates a new internal balance by transferring from PTC ERC20 token.
/// @param _value Token transfered to internal balance.
function addBalanceERC20(uint64 _value) external {
internal_balances[msg.sender] = internal_balances[msg.sender].add(_value);
// transferFrom deposit from sender to contract
// ! needs prior approval on token contract.
require(token.transferFrom(msg.sender, address(this), _value));
}
/// @notice Transfers tokens from internal balance to PTC ERC20 token.
/// @param _value Token amount to return.
function returnBalanceERC20(uint64 _value) external {
internal_balances[msg.sender] = internal_balances[msg.sender].sub(_value); // test S21
require(token.transfer(msg.sender, _value));
}
/// @notice Returns user internal balance.
function balanceOf(address _address) external view
returns(uint64)
{
return (internal_balances[_address]); // test U1
}
/// @notice Change address where fee is transferred
/// @param _network_fee_address Address where network_fee is transferred.
function setNetworkFeeAddress(address _network_fee_address) external { // test S24
require(msg.sender == network_fee_address);
network_fee_address = _network_fee_address;
}
/// @notice Change network fee value. It is limited from 0 to 10%.
/// @param _network_fee Fee that goes to network_fee_address from each closed channel balance.
function setNetworkFee(uint32 _network_fee) external { // test S22
require(msg.sender == network_fee_address);
require(_network_fee <= 10000); // test S23
network_fee = _network_fee;
}
/// @notice Creates a new channel between `msg.sender` (Client) and Agent and places
/// the `_deposit` tokens from internal_balances to channel.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _deposit The amount of tokens that the Client escrows.
function createChannel(address _agent_address, bytes32 _offering_hash, uint64 _deposit) external {
require(_deposit >= service_offering_s[_offering_hash].min_deposit); // test S4
require(internal_balances[msg.sender] >= _deposit); // test S5
decreaseOfferingSupply(_agent_address, _offering_hash);
createChannelPrivate(msg.sender, _agent_address, _offering_hash, _deposit);
internal_balances[msg.sender] = internal_balances[msg.sender].sub(_deposit); //test S5
emit LogChannelCreated(_agent_address, msg.sender, _offering_hash, _deposit); //test E1
}
/// @notice Increase the channel deposit with `_added_deposit`.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _open_block_number The block number at which a channel between the
/// Client and Agent was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _added_deposit The added token deposit with which the current deposit is increased.
function topUpChannel(
address _agent_address,
uint32 _open_block_number,
bytes32 _offering_hash,
uint64 _added_deposit)
external
{
updateInternalBalanceStructs(
msg.sender,
_agent_address,
_open_block_number,
_offering_hash,
_added_deposit
);
internal_balances[msg.sender] = internal_balances[msg.sender].sub(_added_deposit);
}
/// @notice Function called by the Client or Agent, with all the needed
/// signatures to close the channel and settle immediately.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _open_block_number The block number at which a channel between the
/// Client and Agent was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _balance The amount of tokens owed by the Client to the Agent.
/// @param _balance_msg_sig The balance message signed by the Client.
/// @param _closing_sig The Agent's signed balance message, containing the Client's address.
function cooperativeClose(
address _agent_address,
uint32 _open_block_number,
bytes32 _offering_hash,
uint64 _balance,
bytes calldata _balance_msg_sig,
bytes calldata _closing_sig)
external
{
// Derive Client address from signed balance proof
address sender = extractSignature(_agent_address, _open_block_number, _offering_hash, _balance, _balance_msg_sig, true);
// Derive Agent address from closing signature
address receiver = extractSignature(sender, _open_block_number, _offering_hash, _balance, _closing_sig, false);
require(receiver == _agent_address); // tests S6, I1a-I1f
// Both signatures have been verified and the channel can be settled.
settleChannel(sender, receiver, _open_block_number, _offering_hash, _balance);
emit LogCooperativeChannelClose(receiver, sender, _offering_hash, _open_block_number, _balance); // test E7
}
/// @notice Client requests the closing of the channel and starts the remove period.
/// This can only happen once.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _open_block_number The block number at which a channel between
/// the Client and Agent was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _balance The amount of tokens owed by the Client to the Agent.
function uncooperativeClose(
address _agent_address,
uint32 _open_block_number,
bytes32 _offering_hash,
uint64 _balance)
external
{
bytes32 key = getKey(msg.sender, _agent_address, _open_block_number, _offering_hash);
require(channels[key].open_block_number > 0); // test S9
require(closing_requests[key].settle_block_number == 0); // test S10
require(_balance <= channels[key].deposit); // test S11
// Mark channel as closed
closing_requests[key].settle_block_number = uint32(block.number) + challenge_period;
require(closing_requests[key].settle_block_number > block.number);
closing_requests[key].closing_balance = _balance;
emit LogChannelCloseRequested(_agent_address, msg.sender, _offering_hash, _open_block_number, _balance); // test E3
}
/// @notice Function called by the Client after the remove period has ended, in order to
/// settle and delete the channel, in case the Agent has not closed the channel himself.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _open_block_number The block number at which a channel between
/// the Client and Agent was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
function settle(address _agent_address, uint32 _open_block_number, bytes32 _offering_hash) external {
bytes32 key = getKey(msg.sender, _agent_address, _open_block_number, _offering_hash);
// Make sure an uncooperativeClose has been initiated
require(closing_requests[key].settle_block_number > 0); // test S7
// Make sure the challenge_period has ended
require(block.number > closing_requests[key].settle_block_number); // test S8
uint64 balance = closing_requests[key].closing_balance;
settleChannel(msg.sender, _agent_address, _open_block_number, _offering_hash,
closing_requests[key].closing_balance
);
emit LogUnCooperativeChannelClose(_agent_address, msg.sender, _offering_hash,
_open_block_number, balance
); // test E9
}
/// @notice Function for retrieving information about a channel.
/// @param _client_address The address of Client hat sends tokens.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _open_block_number The block number at which a channel between the
/// Client and Agent was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @return Channel information (unique_identifier, deposit, settle_block_number, closing_balance).
function getChannelInfo(
address _client_address,
address _agent_address,
uint32 _open_block_number,
bytes32 _offering_hash)
external
view
returns (uint64, uint32, uint64)
{
bytes32 key = getKey(_client_address, _agent_address, _open_block_number, _offering_hash);
return (
channels[key].deposit,
closing_requests[key].settle_block_number,
closing_requests[key].closing_balance
);
}
function getOfferingInfo(bytes32 offering_hash)
external
view
returns(address, uint64, uint16, uint16, uint32)
{
ServiceOffering memory offering = service_offering_s[offering_hash];
return (offering.agent_address,
offering.min_deposit,
offering.max_supply,
offering.current_supply,
offering.update_block_number
);
// test U2
}
/*
* Public functions
*/
/// @notice Called by Agent to register service offering
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _min_deposit Minimum deposit that Client should place to open state channel.
/// @param _max_supply Maximum supply of services according to service offerings.
function registerServiceOffering (
bytes32 _offering_hash,
uint64 _min_deposit,
uint16 _max_supply,
uint8 _source_type,
string calldata _source)
external
{
// Service offering not exists, test S2
require(service_offering_s[_offering_hash].update_block_number == 0);
//Agent deposit greater than max allowed, test S1
require(_min_deposit.mul(_max_supply) < channel_deposit_bugbounty_limit);
require(_min_deposit > 0); // zero deposit is not allowed, test S3
service_offering_s[_offering_hash] = ServiceOffering(_min_deposit,
msg.sender,
_max_supply,
_max_supply,
uint32(block.number)
);
// Substitute deposit amount for each offering slot from agent's internal balance
// Service provider internal balance must be not less then _min_deposit * _max_supply
internal_balances[msg.sender] = internal_balances[msg.sender].sub(_min_deposit.mul(_max_supply)); // test S26
emit LogOfferingCreated(msg.sender, _offering_hash, _min_deposit, _max_supply, _source_type, _source); // test E4
}
/// @notice Called by Agent to permanently deactivate service offering.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
function removeServiceOffering (
bytes32 _offering_hash)
external
{
require(service_offering_s[_offering_hash].update_block_number > 0); // test S13
// only creator can delete his offering
assert(service_offering_s[_offering_hash].agent_address == msg.sender); // test S14
// At least remove_period blocks were mined after last offering structure update
require(service_offering_s[_offering_hash].update_block_number + remove_period < block.number); // test S15
// return Agent's deposit back to his internal balance
internal_balances[msg.sender] = internal_balances[msg.sender].add(
// it's safe because it was checked in registerServiceOffering
service_offering_s[_offering_hash].min_deposit * service_offering_s[_offering_hash].max_supply
);
// this marks offering as deleted
service_offering_s[_offering_hash].update_block_number = 0;
emit LogOfferingDeleted(msg.sender, _offering_hash); // test E5
}
/// @notice Called by Agent to signal that service offering is actual
/// @param _offering_hash Service Offering hash that uniquely identifies it.
function popupServiceOffering (
bytes32 _offering_hash,
uint8 _source_type,
string calldata _source)
external
{
require(service_offering_s[_offering_hash].update_block_number > 0); // Service offering already exists, test S16
// At least popup_period blocks were mined after last offering structure update
require(service_offering_s[_offering_hash].update_block_number + popup_period < block.number); // test S16a
require(service_offering_s[_offering_hash].agent_address == msg.sender); // test S17
// require(block.number > service_offering_s[_offering_hash].update_block_number);
ServiceOffering memory offering = service_offering_s[_offering_hash];
service_offering_s[_offering_hash].update_block_number = uint32(block.number);
emit LogOfferingPopedUp(msg.sender,
_offering_hash,
offering.min_deposit,
offering.current_supply,
_source_type, _source
); // test E8
}
/// @notice Returns the sender address extracted from the balance proof or closing signature.
/// @param _address The address of Agent or Client that receives/sends tokens.
/// @param _open_block_number The block number at which a channel between the
/// Client and Agent was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _balance The amount of tokens owed by the Client to the Agent.
/// @param _msg_sig The balance message signed by the Client or Agent (depends on _type).
/// @param _type true - extract from BalanceProofSignature signed by Client,
/// false - extract from ClosingSignature signed by Agent
/// @return Address of the balance proof signer.
function extractSignature(
address _address,
uint32 _open_block_number,
bytes32 _offering_hash,
uint64 _balance,
bytes memory _msg_sig,
bool _type)
public
view
returns (address)
{
// The hashed strings should be kept in sync with this function's parameters
// (variable names and types).
bytes32 message_hash =
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",
keccak256(abi.encodePacked(
_type ? 'Privatix: sender balance proof signature' : 'Privatix: receiver closing signature',
_address,
_open_block_number,
_offering_hash,
_balance,
address(this)
))
));
// Derive address from signature
address signer = ECVerify.ecverify(message_hash, _msg_sig);
return signer;
}
/// @notice Returns the unique channel identifier used in the contract.
/// @param _client_address The address of Client that sends tokens.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _open_block_number The block number at which a channel between the
/// Client and Agent was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @return Unique channel identifier.
function getKey(
address _client_address,
address _agent_address,
uint32 _open_block_number,
bytes32 _offering_hash)
public
pure
returns (bytes32 data)
{
return keccak256(abi.encodePacked(_client_address, _agent_address, _open_block_number, _offering_hash));
}
/*
* Private functions
*/
/// @notice Increases available service offering supply.
/// @param _agent_address The address of Agent that created service offering.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @return True in both case, when Service Offering still active or already deactivated.
function increaseOfferingSupply(address _agent_address, bytes32 _offering_hash)
private
returns (bool)
{
require(service_offering_s[_offering_hash].current_supply < service_offering_s[_offering_hash].max_supply);
// Verify that Agent owns this offering
require(service_offering_s[_offering_hash].agent_address == _agent_address);
// saving gas, as no need to update state
if(service_offering_s[_offering_hash].update_block_number == 0) return true;
service_offering_s[_offering_hash].current_supply = service_offering_s[_offering_hash].current_supply+1;
return true;
}
/// @notice Decreases available service offering supply.
/// @param _agent_address The address of Agent that created service offering.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
function decreaseOfferingSupply(address _agent_address, bytes32 _offering_hash)
private
{
require(service_offering_s[_offering_hash].update_block_number > 0);
require(service_offering_s[_offering_hash].agent_address == _agent_address);
require(service_offering_s[_offering_hash].current_supply > 0); // test I5
service_offering_s[_offering_hash].current_supply = service_offering_s[_offering_hash].current_supply-1;
}
/// @dev Creates a new channel between a Client and a Agent.
/// @param _client_address The address of Client that sends tokens.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _deposit The amount of tokens that the Client escrows.
function createChannelPrivate(address _client_address,
address _agent_address,
bytes32 _offering_hash,
uint64 _deposit) private {
require(_deposit <= channel_deposit_bugbounty_limit);
uint32 open_block_number = uint32(block.number);
// Create unique identifier from sender, receiver and current block number
bytes32 key = getKey(_client_address, _agent_address, open_block_number, _offering_hash);
require(channels[key].deposit == 0);
require(channels[key].open_block_number == 0);
require(closing_requests[key].settle_block_number == 0);
// Store channel information
channels[key] = Channel({deposit: _deposit, open_block_number: open_block_number});
}
/// @dev Updates internal balance Structures when the sender adds tokens to the channel.
/// @param _client_address The address that sends tokens.
/// @param _agent_address The address that receives tokens.
/// @param _open_block_number The block number at which a channel between the
/// sender and receiver was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _added_deposit The added token deposit with which the current deposit is increased.
function updateInternalBalanceStructs(
address _client_address,
address _agent_address,
uint32 _open_block_number,
bytes32 _offering_hash,
uint64 _added_deposit)
private
{
require(_added_deposit > 0);
require(_open_block_number > 0);
bytes32 key = getKey(_client_address, _agent_address, _open_block_number, _offering_hash);
require(channels[key].deposit > 0);
require(closing_requests[key].settle_block_number == 0);
require(channels[key].deposit + _added_deposit <= channel_deposit_bugbounty_limit);
channels[key].deposit += _added_deposit;
assert(channels[key].deposit > _added_deposit);
emit LogChannelToppedUp(_agent_address, _client_address, _offering_hash, _open_block_number, _added_deposit); // test E2
}
/// @dev Deletes the channel and settles by transferring the balance to the Agent
/// and the rest of the deposit back to the Client.
/// @param _client_address The address of Client that sends tokens.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _open_block_number The block number at which a channel between the
/// sender and receiver was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _balance The amount of tokens owed by the sender to the receiver.
function settleChannel(
address _client_address,
address _agent_address,
uint32 _open_block_number,
bytes32 _offering_hash,
uint64 _balance)
private
{
bytes32 key = getKey(_client_address, _agent_address, _open_block_number, _offering_hash);
Channel memory channel = channels[key];
require(channel.open_block_number > 0);
require(_balance <= channel.deposit);
// Remove closed channel structures
// channel.open_block_number will become 0
delete channels[key];
delete closing_requests[key];
require(increaseOfferingSupply(_agent_address, _offering_hash));
// Send _balance to the receiver, as it is always <= deposit
uint64 fee = 0;
if(network_fee > 0) {
fee = (_balance/100000)*network_fee; // it's safe because network_fee can't be more than 10000
internal_balances[network_fee_address] = internal_balances[network_fee_address].add(fee);
_balance -= fee;
}
internal_balances[_agent_address] = internal_balances[_agent_address].add(_balance);
// Send deposit - balance back to Client
internal_balances[_client_address] = internal_balances[_client_address].add(channel.deposit - _balance - fee); // I4 test
}
/*
* Internal functions
*/
/// @dev Check if a contract exists.
/// @param _contract The address of the contract to check for.
/// @return True if a contract exists, false otherwise
function addressHasCode(address _contract) private view returns (bool) {
uint size;
assembly {
size := extcodesize(_contract)
}
return size > 0;
}
}
pragma solidity 0.5.8;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath64 {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint64 a, uint64 b) internal pure returns (uint64) {
if (a == 0) {
return 0;
}
uint64 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint64 a, uint64 b) internal pure returns (uint64) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint64 a, uint64 b) internal pure returns (uint64) {
uint64 c = a + b;
assert(c >= a);
return c;
}
}
pragma solidity 0.5.8;
library ECVerify {
function ecverify(bytes32 hash, bytes memory signature) internal pure returns (address signature_address) {
require(signature.length == 65);
bytes32 r;
bytes32 s;
uint8 v;
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
// Here we are loading the last 32 bytes, including 31 bytes of 's'.
v := byte(0, mload(add(signature, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible
if (v < 27) {
v += 27;
}
require(v == 27 || v == 28);
signature_address = ecrecover(hash, v, r, s);
// ecrecover returns zero on error
require(signature_address != address(0x0));
return signature_address;
}
}
pragma solidity 0.5.8;
import './ERC20Basic.sol';
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity 0.5.8;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
pragma solidity 0.5.8;
contract Migrations {
address public owner;
uint public last_completed_migration;
modifier restricted() {
if (msg.sender == owner) _;
}
constructor() public {
owner = msg.sender;
}
function setCompleted(uint completed) public restricted {
last_completed_migration = completed;
}
function upgrade(address new_address) public restricted {
Migrations upgraded = Migrations(new_address);
upgraded.setCompleted(last_completed_migration);
}
}
pragma solidity 0.5.8;
contract MultiOwners {
event AccessGrant(address indexed owner);
event AccessRevoke(address indexed owner);
mapping(address => bool) owners;
constructor() public {
owners[msg.sender] = true;
}
modifier onlyOwner() {
require(owners[msg.sender] == true);
_;
}
function isOwner() view public returns (bool) {
return owners[msg.sender] ? true : false;
}
function checkOwner(address maybe_owner) view public returns (bool) {
return owners[maybe_owner] ? true : false;
}
function grant(address _owner) public onlyOwner {
owners[_owner] = true;
emit AccessGrant(_owner);
}
function revoke(address _owner) public onlyOwner {
require(msg.sender != _owner);
owners[_owner] = false;
emit AccessRevoke(_owner);
}
}
pragma solidity 0.5.8;
import './ERC20.sol';
import './ECVerify.sol';
import './SafeMath64.sol';
/// @title Privatix Service Contract.
contract PrivatixServiceContract {
using SafeMath64 for uint64;
/*
* Data structures
*/
// Number of blocks Agent must wait from last popupServiceOffering or from registerServiceOffering before
// he can popupServiceOffering.
uint32 public popup_period;
// Number of blocks to wait from an uncooperativeClose initiated by the Client
// in order to give the Agent a chance to respond with a balance proof
// in case the sender cheats. After the remove period, the sender can settle
// and delete the channel.
uint32 public challenge_period;
// Number of blocks Agent will wait from registerServiceOffering or from last popupServiceOffering before
// he can delete service offering and receive Agent's deposit back.
uint32 public remove_period;
// Fee that goes to network_fee_address from each closed channel balance.
uint32 public network_fee;
// Address where network_fee is transferred.
address public network_fee_address;
// We temporarily limit total token deposits in a channel to 300 PRIX.
// This is just for the bug bounty release, as a safety measure.
uint64 public constant channel_deposit_bugbounty_limit = 10 ** 8 * 300;
ERC20 public token;
mapping (bytes32 => Channel) private channels;
mapping (bytes32 => ClosingRequest) private closing_requests;
mapping (address => uint64) private internal_balances;
mapping(bytes32 => ServiceOffering) private service_offering_s;
// 52 bytes
struct ServiceOffering{
uint64 min_deposit; // bytes8 - Minimum deposit that Client should place to open state channel.
address agent_address; //bytes20 - Address of Agent.
uint16 max_supply; // bytes2 - Maximum supply of services according to service offerings.
uint16 current_supply; // bytes2 - Currently remaining available supply.
// bytes4 - Last block number when service offering was created, popped-up or channel opened.
// If 0 - offering was removed.
uint32 update_block_number;
}
// 28 bytes
struct Channel {
// uint64 is the maximum uint size needed for deposit based on a
// log2(10^8 * 1275455 token totalSupply) = 46.85.
uint64 deposit;
// Block number at which the channel was opened. Used in creating
// a unique identifier for the channel between a sender and receiver.
// Supports creation of multiple channels between the 2 parties and prevents
// replay of messages in later channels.
uint32 open_block_number;
}
// 28 bytes
struct ClosingRequest {
// Number of tokens owed by the Client when closing the channel.
uint64 closing_balance;
// Block number at which the remove period ends, in case it has been initiated.
uint32 settle_block_number;
}
/*
* Events
*/
event LogChannelCreated(
address indexed _agent,
address indexed _client,
bytes32 indexed _offering_hash,
uint64 _deposit);
event LogChannelToppedUp(
address indexed _agent,
address indexed _client,
bytes32 indexed _offering_hash,
uint32 _open_block_number,
uint64 _added_deposit);
event LogChannelCloseRequested(
address indexed _agent,
address indexed _client,
bytes32 indexed _offering_hash,
uint32 _open_block_number,
uint64 _balance);
event LogOfferingCreated(
address indexed _agent,
bytes32 indexed _offering_hash,
uint64 indexed _min_deposit,
uint16 _current_supply,
uint8 _source_type,
string _source);
event LogOfferingDeleted(
address indexed _agent,
bytes32 indexed _offering_hash);
event LogOfferingPopedUp(
address indexed _agent,
bytes32 indexed _offering_hash,
uint64 indexed _min_deposit,
uint16 _current_supply,
uint8 _source_type,
string _source);
event LogCooperativeChannelClose(
address indexed _agent,
address indexed _client,
bytes32 indexed _offering_hash,
uint32 _open_block_number,
uint64 _balance);
event LogUnCooperativeChannelClose(
address indexed _agent,
address indexed _client,
bytes32 indexed _offering_hash,
uint32 _open_block_number,
uint64 _balance);
/*
* Modifiers
*/
/*
* Constructor
*/
/// @notice Constructor for creating the Privatix Service Contract.
/// @param _token_address The address of the PTC (Privatix Token Contract)
/// @param _popup_period A fixed number of blocks representing the pop-up period.
/// @param _remove_period A fixed number of blocks representing the remove period.
/// @param _challenge_period A fixed number of blocks representing the challenge period.
/// We enforce a minimum of 500 blocks waiting period.
/// after a sender requests the closing of the channel without the receiver's signature.
constructor(
address _token_address,
address _network_fee_address,
uint32 _popup_period,
uint32 _remove_period,
uint32 _challenge_period
) public {
require(_token_address != address(0x0));
require(addressHasCode(_token_address));
require(_network_fee_address != address(0x0));
require(_remove_period >= 100);
require(_popup_period >= 500);
require(_challenge_period >= 5000);
token = ERC20(_token_address);
// Check if the contract is indeed a token contract
require(token.totalSupply() > 0);
network_fee_address = _network_fee_address;
popup_period = _popup_period;
remove_period = _remove_period;
challenge_period = _challenge_period;
}
/*
* External functions
*/
/// @notice Creates a new internal balance by transferring from PTC ERC20 token.
/// @param _value Token transfered to internal balance.
function addBalanceERC20(uint64 _value) external {
internal_balances[msg.sender] = internal_balances[msg.sender].add(_value);
// transferFrom deposit from sender to contract
// ! needs prior approval on token contract.
require(token.transferFrom(msg.sender, address(this), _value));
}
/// @notice Transfers tokens from internal balance to PTC ERC20 token.
/// @param _value Token amount to return.
function returnBalanceERC20(uint64 _value) external {
internal_balances[msg.sender] = internal_balances[msg.sender].sub(_value); // test S21
require(token.transfer(msg.sender, _value));
}
/// @notice Returns user internal balance.
function balanceOf(address _address) external view
returns(uint64)
{
return (internal_balances[_address]); // test U1
}
/// @notice Change address where fee is transferred
/// @param _network_fee_address Address where network_fee is transferred.
function setNetworkFeeAddress(address _network_fee_address) external { // test S24
require(msg.sender == network_fee_address);
network_fee_address = _network_fee_address;
}
/// @notice Change network fee value. It is limited from 0 to 10%.
/// @param _network_fee Fee that goes to network_fee_address from each closed channel balance.
function setNetworkFee(uint32 _network_fee) external { // test S22
require(msg.sender == network_fee_address);
require(_network_fee <= 10000); // test S23
network_fee = _network_fee;
}
/// @notice Creates a new channel between `msg.sender` (Client) and Agent and places
/// the `_deposit` tokens from internal_balances to channel.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _deposit The amount of tokens that the Client escrows.
function createChannel(address _agent_address, bytes32 _offering_hash, uint64 _deposit) external {
require(_deposit >= service_offering_s[_offering_hash].min_deposit); // test S4
require(internal_balances[msg.sender] >= _deposit); // test S5
decreaseOfferingSupply(_agent_address, _offering_hash);
createChannelPrivate(msg.sender, _agent_address, _offering_hash, _deposit);
internal_balances[msg.sender] = internal_balances[msg.sender].sub(_deposit); //test S5
emit LogChannelCreated(_agent_address, msg.sender, _offering_hash, _deposit); //test E1
}
/// @notice Increase the channel deposit with `_added_deposit`.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _open_block_number The block number at which a channel between the
/// Client and Agent was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _added_deposit The added token deposit with which the current deposit is increased.
function topUpChannel(
address _agent_address,
uint32 _open_block_number,
bytes32 _offering_hash,
uint64 _added_deposit)
external
{
updateInternalBalanceStructs(
msg.sender,
_agent_address,
_open_block_number,
_offering_hash,
_added_deposit
);
internal_balances[msg.sender] = internal_balances[msg.sender].sub(_added_deposit);
}
/// @notice Function called by the Client or Agent, with all the needed
/// signatures to close the channel and settle immediately.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _open_block_number The block number at which a channel between the
/// Client and Agent was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _balance The amount of tokens owed by the Client to the Agent.
/// @param _balance_msg_sig The balance message signed by the Client.
/// @param _closing_sig The Agent's signed balance message, containing the Client's address.
function cooperativeClose(
address _agent_address,
uint32 _open_block_number,
bytes32 _offering_hash,
uint64 _balance,
bytes calldata _balance_msg_sig,
bytes calldata _closing_sig)
external
{
// Derive Client address from signed balance proof
address sender = extractSignature(_agent_address, _open_block_number, _offering_hash, _balance, _balance_msg_sig, true);
// Derive Agent address from closing signature
address receiver = extractSignature(sender, _open_block_number, _offering_hash, _balance, _closing_sig, false);
require(receiver == _agent_address); // tests S6, I1a-I1f
// Both signatures have been verified and the channel can be settled.
settleChannel(sender, receiver, _open_block_number, _offering_hash, _balance);
emit LogCooperativeChannelClose(receiver, sender, _offering_hash, _open_block_number, _balance); // test E7
}
/// @notice Client requests the closing of the channel and starts the remove period.
/// This can only happen once.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _open_block_number The block number at which a channel between
/// the Client and Agent was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _balance The amount of tokens owed by the Client to the Agent.
function uncooperativeClose(
address _agent_address,
uint32 _open_block_number,
bytes32 _offering_hash,
uint64 _balance)
external
{
bytes32 key = getKey(msg.sender, _agent_address, _open_block_number, _offering_hash);
require(channels[key].open_block_number > 0); // test S9
require(closing_requests[key].settle_block_number == 0); // test S10
require(_balance <= channels[key].deposit); // test S11
// Mark channel as closed
closing_requests[key].settle_block_number = uint32(block.number) + challenge_period;
require(closing_requests[key].settle_block_number > block.number);
closing_requests[key].closing_balance = _balance;
emit LogChannelCloseRequested(_agent_address, msg.sender, _offering_hash, _open_block_number, _balance); // test E3
}
/// @notice Function called by the Client after the remove period has ended, in order to
/// settle and delete the channel, in case the Agent has not closed the channel himself.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _open_block_number The block number at which a channel between
/// the Client and Agent was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
function settle(address _agent_address, uint32 _open_block_number, bytes32 _offering_hash) external {
bytes32 key = getKey(msg.sender, _agent_address, _open_block_number, _offering_hash);
// Make sure an uncooperativeClose has been initiated
require(closing_requests[key].settle_block_number > 0); // test S7
// Make sure the challenge_period has ended
require(block.number > closing_requests[key].settle_block_number); // test S8
uint64 balance = closing_requests[key].closing_balance;
settleChannel(msg.sender, _agent_address, _open_block_number, _offering_hash,
closing_requests[key].closing_balance
);
emit LogUnCooperativeChannelClose(_agent_address, msg.sender, _offering_hash,
_open_block_number, balance
); // test E9
}
/// @notice Function for retrieving information about a channel.
/// @param _client_address The address of Client hat sends tokens.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _open_block_number The block number at which a channel between the
/// Client and Agent was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @return Channel information (unique_identifier, deposit, settle_block_number, closing_balance).
function getChannelInfo(
address _client_address,
address _agent_address,
uint32 _open_block_number,
bytes32 _offering_hash)
external
view
returns (uint64, uint32, uint64)
{
bytes32 key = getKey(_client_address, _agent_address, _open_block_number, _offering_hash);
return (
channels[key].deposit,
closing_requests[key].settle_block_number,
closing_requests[key].closing_balance
);
}
function getOfferingInfo(bytes32 offering_hash)
external
view
returns(address, uint64, uint16, uint16, uint32)
{
ServiceOffering memory offering = service_offering_s[offering_hash];
return (offering.agent_address,
offering.min_deposit,
offering.max_supply,
offering.current_supply,
offering.update_block_number
);
// test U2
}
/*
* Public functions
*/
/// @notice Called by Agent to register service offering
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _min_deposit Minimum deposit that Client should place to open state channel.
/// @param _max_supply Maximum supply of services according to service offerings.
function registerServiceOffering (
bytes32 _offering_hash,
uint64 _min_deposit,
uint16 _max_supply,
uint8 _source_type,
string calldata _source)
external
{
// Service offering not exists, test S2
require(service_offering_s[_offering_hash].update_block_number == 0);
//Agent deposit greater than max allowed, test S1
require(_min_deposit.mul(_max_supply) < channel_deposit_bugbounty_limit);
require(_min_deposit > 0); // zero deposit is not allowed, test S3
service_offering_s[_offering_hash] = ServiceOffering(_min_deposit,
msg.sender,
_max_supply,
_max_supply,
uint32(block.number)
);
// Substitute deposit amount for each offering slot from agent's internal balance
// Service provider internal balance must be not less then _min_deposit * _max_supply
internal_balances[msg.sender] = internal_balances[msg.sender].sub(_min_deposit.mul(_max_supply)); // test S26
emit LogOfferingCreated(msg.sender, _offering_hash, _min_deposit, _max_supply, _source_type, _source); // test E4
}
/// @notice Called by Agent to permanently deactivate service offering.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
function removeServiceOffering (
bytes32 _offering_hash)
external
{
require(service_offering_s[_offering_hash].update_block_number > 0); // test S13
// only creator can delete his offering
assert(service_offering_s[_offering_hash].agent_address == msg.sender); // test S14
// At least remove_period blocks were mined after last offering structure update
require(service_offering_s[_offering_hash].update_block_number + remove_period < block.number); // test S15
// return Agent's deposit back to his internal balance
internal_balances[msg.sender] = internal_balances[msg.sender].add(
// it's safe because it was checked in registerServiceOffering
service_offering_s[_offering_hash].min_deposit * service_offering_s[_offering_hash].max_supply
);
// this marks offering as deleted
service_offering_s[_offering_hash].update_block_number = 0;
emit LogOfferingDeleted(msg.sender, _offering_hash); // test E5
}
/// @notice Called by Agent to signal that service offering is actual
/// @param _offering_hash Service Offering hash that uniquely identifies it.
function popupServiceOffering (
bytes32 _offering_hash,
uint8 _source_type,
string calldata _source)
external
{
require(service_offering_s[_offering_hash].update_block_number > 0); // Service offering already exists, test S16
// At least popup_period blocks were mined after last offering structure update
require(service_offering_s[_offering_hash].update_block_number + popup_period < block.number); // test S16a
require(service_offering_s[_offering_hash].agent_address == msg.sender); // test S17
// require(block.number > service_offering_s[_offering_hash].update_block_number);
ServiceOffering memory offering = service_offering_s[_offering_hash];
service_offering_s[_offering_hash].update_block_number = uint32(block.number);
emit LogOfferingPopedUp(msg.sender,
_offering_hash,
offering.min_deposit,
offering.current_supply,
_source_type, _source
); // test E8
}
/// @notice Returns the sender address extracted from the balance proof or closing signature.
/// @param _address The address of Agent or Client that receives/sends tokens.
/// @param _open_block_number The block number at which a channel between the
/// Client and Agent was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _balance The amount of tokens owed by the Client to the Agent.
/// @param _msg_sig The balance message signed by the Client or Agent (depends on _type).
/// @param _type true - extract from BalanceProofSignature signed by Client,
/// false - extract from ClosingSignature signed by Agent
/// @return Address of the balance proof signer.
function extractSignature(
address _address,
uint32 _open_block_number,
bytes32 _offering_hash,
uint64 _balance,
bytes memory _msg_sig,
bool _type)
public
view
returns (address)
{
// The hashed strings should be kept in sync with this function's parameters
// (variable names and types).
bytes32 message_hash =
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",
keccak256(abi.encodePacked(
_type ? 'Privatix: sender balance proof signature' : 'Privatix: receiver closing signature',
_address,
_open_block_number,
_offering_hash,
_balance,
address(this)
))
));
// Derive address from signature
address signer = ECVerify.ecverify(message_hash, _msg_sig);
return signer;
}
/// @notice Returns the unique channel identifier used in the contract.
/// @param _client_address The address of Client that sends tokens.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _open_block_number The block number at which a channel between the
/// Client and Agent was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @return Unique channel identifier.
function getKey(
address _client_address,
address _agent_address,
uint32 _open_block_number,
bytes32 _offering_hash)
public
pure
returns (bytes32 data)
{
return keccak256(abi.encodePacked(_client_address, _agent_address, _open_block_number, _offering_hash));
}
/*
* Private functions
*/
/// @notice Increases available service offering supply.
/// @param _agent_address The address of Agent that created service offering.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @return True in both case, when Service Offering still active or already deactivated.
function increaseOfferingSupply(address _agent_address, bytes32 _offering_hash)
private
returns (bool)
{
require(service_offering_s[_offering_hash].current_supply < service_offering_s[_offering_hash].max_supply);
// Verify that Agent owns this offering
require(service_offering_s[_offering_hash].agent_address == _agent_address);
// saving gas, as no need to update state
if(service_offering_s[_offering_hash].update_block_number == 0) return true;
service_offering_s[_offering_hash].current_supply = service_offering_s[_offering_hash].current_supply+1;
return true;
}
/// @notice Decreases available service offering supply.
/// @param _agent_address The address of Agent that created service offering.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
function decreaseOfferingSupply(address _agent_address, bytes32 _offering_hash)
private
{
require(service_offering_s[_offering_hash].update_block_number > 0);
require(service_offering_s[_offering_hash].agent_address == _agent_address);
require(service_offering_s[_offering_hash].current_supply > 0); // test I5
service_offering_s[_offering_hash].current_supply = service_offering_s[_offering_hash].current_supply-1;
}
/// @dev Creates a new channel between a Client and a Agent.
/// @param _client_address The address of Client that sends tokens.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _deposit The amount of tokens that the Client escrows.
function createChannelPrivate(address _client_address,
address _agent_address,
bytes32 _offering_hash,
uint64 _deposit) private {
require(_deposit <= channel_deposit_bugbounty_limit);
uint32 open_block_number = uint32(block.number);
// Create unique identifier from sender, receiver and current block number
bytes32 key = getKey(_client_address, _agent_address, open_block_number, _offering_hash);
require(channels[key].deposit == 0);
require(channels[key].open_block_number == 0);
require(closing_requests[key].settle_block_number == 0);
// Store channel information
channels[key] = Channel({deposit: _deposit, open_block_number: open_block_number});
}
/// @dev Updates internal balance Structures when the sender adds tokens to the channel.
/// @param _client_address The address that sends tokens.
/// @param _agent_address The address that receives tokens.
/// @param _open_block_number The block number at which a channel between the
/// sender and receiver was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _added_deposit The added token deposit with which the current deposit is increased.
function updateInternalBalanceStructs(
address _client_address,
address _agent_address,
uint32 _open_block_number,
bytes32 _offering_hash,
uint64 _added_deposit)
private
{
require(_added_deposit > 0);
require(_open_block_number > 0);
bytes32 key = getKey(_client_address, _agent_address, _open_block_number, _offering_hash);
require(channels[key].deposit > 0);
require(closing_requests[key].settle_block_number == 0);
require(channels[key].deposit + _added_deposit <= channel_deposit_bugbounty_limit);
channels[key].deposit += _added_deposit;
assert(channels[key].deposit > _added_deposit);
emit LogChannelToppedUp(_agent_address, _client_address, _offering_hash, _open_block_number, _added_deposit); // test E2
}
/// @dev Deletes the channel and settles by transferring the balance to the Agent
/// and the rest of the deposit back to the Client.
/// @param _client_address The address of Client that sends tokens.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _open_block_number The block number at which a channel between the
/// sender and receiver was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _balance The amount of tokens owed by the sender to the receiver.
function settleChannel(
address _client_address,
address _agent_address,
uint32 _open_block_number,
bytes32 _offering_hash,
uint64 _balance)
private
{
bytes32 key = getKey(_client_address, _agent_address, _open_block_number, _offering_hash);
Channel memory channel = channels[key];
require(channel.open_block_number > 0);
require(_balance <= channel.deposit);
// Remove closed channel structures
// channel.open_block_number will become 0
delete channels[key];
delete closing_requests[key];
require(increaseOfferingSupply(_agent_address, _offering_hash));
// Send _balance to the receiver, as it is always <= deposit
uint64 fee = 0;
if(network_fee > 0) {
fee = (_balance/100000)*network_fee; // it's safe because network_fee can't be more than 10000
internal_balances[network_fee_address] = internal_balances[network_fee_address].add(fee);
_balance -= fee;
}
internal_balances[_agent_address] = internal_balances[_agent_address].add(_balance);
// Send deposit - balance back to Client
internal_balances[_client_address] = internal_balances[_client_address].add(channel.deposit - _balance - fee); // I4 test
}
/*
* Internal functions
*/
/// @dev Check if a contract exists.
/// @param _contract The address of the contract to check for.
/// @return True if a contract exists, false otherwise
function addressHasCode(address _contract) private view returns (bool) {
uint size;
assembly {
size := extcodesize(_contract)
}
return size > 0;
}
}
pragma solidity 0.5.8;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath64 {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint64 a, uint64 b) internal pure returns (uint64) {
if (a == 0) {
return 0;
}
uint64 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint64 a, uint64 b) internal pure returns (uint64) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint64 a, uint64 b) internal pure returns (uint64) {
uint64 c = a + b;
assert(c >= a);
return c;
}
}
pragma solidity 0.5.8;
library ECVerify {
function ecverify(bytes32 hash, bytes memory signature) internal pure returns (address signature_address) {
require(signature.length == 65);
bytes32 r;
bytes32 s;
uint8 v;
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
// Here we are loading the last 32 bytes, including 31 bytes of 's'.
v := byte(0, mload(add(signature, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible
if (v < 27) {
v += 27;
}
require(v == 27 || v == 28);
signature_address = ecrecover(hash, v, r, s);
// ecrecover returns zero on error
require(signature_address != address(0x0));
return signature_address;
}
}
pragma solidity 0.5.8;
import './ERC20Basic.sol';
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity 0.5.8;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
pragma solidity 0.5.8;
contract Migrations {
address public owner;
uint public last_completed_migration;
modifier restricted() {
if (msg.sender == owner) _;
}
constructor() public {
owner = msg.sender;
}
function setCompleted(uint completed) public restricted {
last_completed_migration = completed;
}
function upgrade(address new_address) public restricted {
Migrations upgraded = Migrations(new_address);
upgraded.setCompleted(last_completed_migration);
}
}
pragma solidity 0.5.8;
contract MultiOwners {
event AccessGrant(address indexed owner);
event AccessRevoke(address indexed owner);
mapping(address => bool) owners;
constructor() public {
owners[msg.sender] = true;
}
modifier onlyOwner() {
require(owners[msg.sender] == true);
_;
}
function isOwner() view public returns (bool) {
return owners[msg.sender] ? true : false;
}
function checkOwner(address maybe_owner) view public returns (bool) {
return owners[maybe_owner] ? true : false;
}
function grant(address _owner) public onlyOwner {
owners[_owner] = true;
emit AccessGrant(_owner);
}
function revoke(address _owner) public onlyOwner {
require(msg.sender != _owner);
owners[_owner] = false;
emit AccessRevoke(_owner);
}
}
pragma solidity 0.5.8;
import './ERC20.sol';
import './ECVerify.sol';
import './SafeMath64.sol';
/// @title Privatix Service Contract.
contract PrivatixServiceContract {
using SafeMath64 for uint64;
/*
* Data structures
*/
// Number of blocks Agent must wait from last popupServiceOffering or from registerServiceOffering before
// he can popupServiceOffering.
uint32 public popup_period;
// Number of blocks to wait from an uncooperativeClose initiated by the Client
// in order to give the Agent a chance to respond with a balance proof
// in case the sender cheats. After the remove period, the sender can settle
// and delete the channel.
uint32 public challenge_period;
// Number of blocks Agent will wait from registerServiceOffering or from last popupServiceOffering before
// he can delete service offering and receive Agent's deposit back.
uint32 public remove_period;
// Fee that goes to network_fee_address from each closed channel balance.
uint32 public network_fee;
// Address where network_fee is transferred.
address public network_fee_address;
// We temporarily limit total token deposits in a channel to 300 PRIX.
// This is just for the bug bounty release, as a safety measure.
uint64 public constant channel_deposit_bugbounty_limit = 10 ** 8 * 300;
ERC20 public token;
mapping (bytes32 => Channel) private channels;
mapping (bytes32 => ClosingRequest) private closing_requests;
mapping (address => uint64) private internal_balances;
mapping(bytes32 => ServiceOffering) private service_offering_s;
// 52 bytes
struct ServiceOffering{
uint64 min_deposit; // bytes8 - Minimum deposit that Client should place to open state channel.
address agent_address; //bytes20 - Address of Agent.
uint16 max_supply; // bytes2 - Maximum supply of services according to service offerings.
uint16 current_supply; // bytes2 - Currently remaining available supply.
// bytes4 - Last block number when service offering was created, popped-up or channel opened.
// If 0 - offering was removed.
uint32 update_block_number;
}
// 28 bytes
struct Channel {
// uint64 is the maximum uint size needed for deposit based on a
// log2(10^8 * 1275455 token totalSupply) = 46.85.
uint64 deposit;
// Block number at which the channel was opened. Used in creating
// a unique identifier for the channel between a sender and receiver.
// Supports creation of multiple channels between the 2 parties and prevents
// replay of messages in later channels.
uint32 open_block_number;
}
// 28 bytes
struct ClosingRequest {
// Number of tokens owed by the Client when closing the channel.
uint64 closing_balance;
// Block number at which the remove period ends, in case it has been initiated.
uint32 settle_block_number;
}
/*
* Events
*/
event LogChannelCreated(
address indexed _agent,
address indexed _client,
bytes32 indexed _offering_hash,
uint64 _deposit);
event LogChannelToppedUp(
address indexed _agent,
address indexed _client,
bytes32 indexed _offering_hash,
uint32 _open_block_number,
uint64 _added_deposit);
event LogChannelCloseRequested(
address indexed _agent,
address indexed _client,
bytes32 indexed _offering_hash,
uint32 _open_block_number,
uint64 _balance);
event LogOfferingCreated(
address indexed _agent,
bytes32 indexed _offering_hash,
uint64 indexed _min_deposit,
uint16 _current_supply,
uint8 _source_type,
string _source);
event LogOfferingDeleted(
address indexed _agent,
bytes32 indexed _offering_hash);
event LogOfferingPopedUp(
address indexed _agent,
bytes32 indexed _offering_hash,
uint64 indexed _min_deposit,
uint16 _current_supply,
uint8 _source_type,
string _source);
event LogCooperativeChannelClose(
address indexed _agent,
address indexed _client,
bytes32 indexed _offering_hash,
uint32 _open_block_number,
uint64 _balance);
event LogUnCooperativeChannelClose(
address indexed _agent,
address indexed _client,
bytes32 indexed _offering_hash,
uint32 _open_block_number,
uint64 _balance);
/*
* Modifiers
*/
/*
* Constructor
*/
/// @notice Constructor for creating the Privatix Service Contract.
/// @param _token_address The address of the PTC (Privatix Token Contract)
/// @param _popup_period A fixed number of blocks representing the pop-up period.
/// @param _remove_period A fixed number of blocks representing the remove period.
/// @param _challenge_period A fixed number of blocks representing the challenge period.
/// We enforce a minimum of 500 blocks waiting period.
/// after a sender requests the closing of the channel without the receiver's signature.
constructor(
address _token_address,
address _network_fee_address,
uint32 _popup_period,
uint32 _remove_period,
uint32 _challenge_period
) public {
require(_token_address != address(0x0));
require(addressHasCode(_token_address));
require(_network_fee_address != address(0x0));
require(_remove_period >= 100);
require(_popup_period >= 500);
require(_challenge_period >= 5000);
token = ERC20(_token_address);
// Check if the contract is indeed a token contract
require(token.totalSupply() > 0);
network_fee_address = _network_fee_address;
popup_period = _popup_period;
remove_period = _remove_period;
challenge_period = _challenge_period;
}
/*
* External functions
*/
/// @notice Creates a new internal balance by transferring from PTC ERC20 token.
/// @param _value Token transfered to internal balance.
function addBalanceERC20(uint64 _value) external {
internal_balances[msg.sender] = internal_balances[msg.sender].add(_value);
// transferFrom deposit from sender to contract
// ! needs prior approval on token contract.
require(token.transferFrom(msg.sender, address(this), _value));
}
/// @notice Transfers tokens from internal balance to PTC ERC20 token.
/// @param _value Token amount to return.
function returnBalanceERC20(uint64 _value) external {
internal_balances[msg.sender] = internal_balances[msg.sender].sub(_value); // test S21
require(token.transfer(msg.sender, _value));
}
/// @notice Returns user internal balance.
function balanceOf(address _address) external view
returns(uint64)
{
return (internal_balances[_address]); // test U1
}
/// @notice Change address where fee is transferred
/// @param _network_fee_address Address where network_fee is transferred.
function setNetworkFeeAddress(address _network_fee_address) external { // test S24
require(msg.sender == network_fee_address);
network_fee_address = _network_fee_address;
}
/// @notice Change network fee value. It is limited from 0 to 10%.
/// @param _network_fee Fee that goes to network_fee_address from each closed channel balance.
function setNetworkFee(uint32 _network_fee) external { // test S22
require(msg.sender == network_fee_address);
require(_network_fee <= 10000); // test S23
network_fee = _network_fee;
}
/// @notice Creates a new channel between `msg.sender` (Client) and Agent and places
/// the `_deposit` tokens from internal_balances to channel.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _deposit The amount of tokens that the Client escrows.
function createChannel(address _agent_address, bytes32 _offering_hash, uint64 _deposit) external {
require(_deposit >= service_offering_s[_offering_hash].min_deposit); // test S4
require(internal_balances[msg.sender] >= _deposit); // test S5
decreaseOfferingSupply(_agent_address, _offering_hash);
createChannelPrivate(msg.sender, _agent_address, _offering_hash, _deposit);
internal_balances[msg.sender] = internal_balances[msg.sender].sub(_deposit); //test S5
emit LogChannelCreated(_agent_address, msg.sender, _offering_hash, _deposit); //test E1
}
/// @notice Increase the channel deposit with `_added_deposit`.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _open_block_number The block number at which a channel between the
/// Client and Agent was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _added_deposit The added token deposit with which the current deposit is increased.
function topUpChannel(
address _agent_address,
uint32 _open_block_number,
bytes32 _offering_hash,
uint64 _added_deposit)
external
{
updateInternalBalanceStructs(
msg.sender,
_agent_address,
_open_block_number,
_offering_hash,
_added_deposit
);
internal_balances[msg.sender] = internal_balances[msg.sender].sub(_added_deposit);
}
/// @notice Function called by the Client or Agent, with all the needed
/// signatures to close the channel and settle immediately.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _open_block_number The block number at which a channel between the
/// Client and Agent was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _balance The amount of tokens owed by the Client to the Agent.
/// @param _balance_msg_sig The balance message signed by the Client.
/// @param _closing_sig The Agent's signed balance message, containing the Client's address.
function cooperativeClose(
address _agent_address,
uint32 _open_block_number,
bytes32 _offering_hash,
uint64 _balance,
bytes calldata _balance_msg_sig,
bytes calldata _closing_sig)
external
{
// Derive Client address from signed balance proof
address sender = extractSignature(_agent_address, _open_block_number, _offering_hash, _balance, _balance_msg_sig, true);
// Derive Agent address from closing signature
address receiver = extractSignature(sender, _open_block_number, _offering_hash, _balance, _closing_sig, false);
require(receiver == _agent_address); // tests S6, I1a-I1f
// Both signatures have been verified and the channel can be settled.
settleChannel(sender, receiver, _open_block_number, _offering_hash, _balance);
emit LogCooperativeChannelClose(receiver, sender, _offering_hash, _open_block_number, _balance); // test E7
}
/// @notice Client requests the closing of the channel and starts the remove period.
/// This can only happen once.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _open_block_number The block number at which a channel between
/// the Client and Agent was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _balance The amount of tokens owed by the Client to the Agent.
function uncooperativeClose(
address _agent_address,
uint32 _open_block_number,
bytes32 _offering_hash,
uint64 _balance)
external
{
bytes32 key = getKey(msg.sender, _agent_address, _open_block_number, _offering_hash);
require(channels[key].open_block_number > 0); // test S9
require(closing_requests[key].settle_block_number == 0); // test S10
require(_balance <= channels[key].deposit); // test S11
// Mark channel as closed
closing_requests[key].settle_block_number = uint32(block.number) + challenge_period;
require(closing_requests[key].settle_block_number > block.number);
closing_requests[key].closing_balance = _balance;
emit LogChannelCloseRequested(_agent_address, msg.sender, _offering_hash, _open_block_number, _balance); // test E3
}
/// @notice Function called by the Client after the remove period has ended, in order to
/// settle and delete the channel, in case the Agent has not closed the channel himself.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _open_block_number The block number at which a channel between
/// the Client and Agent was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
function settle(address _agent_address, uint32 _open_block_number, bytes32 _offering_hash) external {
bytes32 key = getKey(msg.sender, _agent_address, _open_block_number, _offering_hash);
// Make sure an uncooperativeClose has been initiated
require(closing_requests[key].settle_block_number > 0); // test S7
// Make sure the challenge_period has ended
require(block.number > closing_requests[key].settle_block_number); // test S8
uint64 balance = closing_requests[key].closing_balance;
settleChannel(msg.sender, _agent_address, _open_block_number, _offering_hash,
closing_requests[key].closing_balance
);
emit LogUnCooperativeChannelClose(_agent_address, msg.sender, _offering_hash,
_open_block_number, balance
); // test E9
}
/// @notice Function for retrieving information about a channel.
/// @param _client_address The address of Client hat sends tokens.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _open_block_number The block number at which a channel between the
/// Client and Agent was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @return Channel information (unique_identifier, deposit, settle_block_number, closing_balance).
function getChannelInfo(
address _client_address,
address _agent_address,
uint32 _open_block_number,
bytes32 _offering_hash)
external
view
returns (uint64, uint32, uint64)
{
bytes32 key = getKey(_client_address, _agent_address, _open_block_number, _offering_hash);
return (
channels[key].deposit,
closing_requests[key].settle_block_number,
closing_requests[key].closing_balance
);
}
function getOfferingInfo(bytes32 offering_hash)
external
view
returns(address, uint64, uint16, uint16, uint32)
{
ServiceOffering memory offering = service_offering_s[offering_hash];
return (offering.agent_address,
offering.min_deposit,
offering.max_supply,
offering.current_supply,
offering.update_block_number
);
// test U2
}
/*
* Public functions
*/
/// @notice Called by Agent to register service offering
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _min_deposit Minimum deposit that Client should place to open state channel.
/// @param _max_supply Maximum supply of services according to service offerings.
function registerServiceOffering (
bytes32 _offering_hash,
uint64 _min_deposit,
uint16 _max_supply,
uint8 _source_type,
string calldata _source)
external
{
// Service offering not exists, test S2
require(service_offering_s[_offering_hash].update_block_number == 0);
//Agent deposit greater than max allowed, test S1
require(_min_deposit.mul(_max_supply) < channel_deposit_bugbounty_limit);
require(_min_deposit > 0); // zero deposit is not allowed, test S3
service_offering_s[_offering_hash] = ServiceOffering(_min_deposit,
msg.sender,
_max_supply,
_max_supply,
uint32(block.number)
);
// Substitute deposit amount for each offering slot from agent's internal balance
// Service provider internal balance must be not less then _min_deposit * _max_supply
internal_balances[msg.sender] = internal_balances[msg.sender].sub(_min_deposit.mul(_max_supply)); // test S26
emit LogOfferingCreated(msg.sender, _offering_hash, _min_deposit, _max_supply, _source_type, _source); // test E4
}
/// @notice Called by Agent to permanently deactivate service offering.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
function removeServiceOffering (
bytes32 _offering_hash)
external
{
require(service_offering_s[_offering_hash].update_block_number > 0); // test S13
// only creator can delete his offering
assert(service_offering_s[_offering_hash].agent_address == msg.sender); // test S14
// At least remove_period blocks were mined after last offering structure update
require(service_offering_s[_offering_hash].update_block_number + remove_period < block.number); // test S15
// return Agent's deposit back to his internal balance
internal_balances[msg.sender] = internal_balances[msg.sender].add(
// it's safe because it was checked in registerServiceOffering
service_offering_s[_offering_hash].min_deposit * service_offering_s[_offering_hash].max_supply
);
// this marks offering as deleted
service_offering_s[_offering_hash].update_block_number = 0;
emit LogOfferingDeleted(msg.sender, _offering_hash); // test E5
}
/// @notice Called by Agent to signal that service offering is actual
/// @param _offering_hash Service Offering hash that uniquely identifies it.
function popupServiceOffering (
bytes32 _offering_hash,
uint8 _source_type,
string calldata _source)
external
{
require(service_offering_s[_offering_hash].update_block_number > 0); // Service offering already exists, test S16
// At least popup_period blocks were mined after last offering structure update
require(service_offering_s[_offering_hash].update_block_number + popup_period < block.number); // test S16a
require(service_offering_s[_offering_hash].agent_address == msg.sender); // test S17
// require(block.number > service_offering_s[_offering_hash].update_block_number);
ServiceOffering memory offering = service_offering_s[_offering_hash];
service_offering_s[_offering_hash].update_block_number = uint32(block.number);
emit LogOfferingPopedUp(msg.sender,
_offering_hash,
offering.min_deposit,
offering.current_supply,
_source_type, _source
); // test E8
}
/// @notice Returns the sender address extracted from the balance proof or closing signature.
/// @param _address The address of Agent or Client that receives/sends tokens.
/// @param _open_block_number The block number at which a channel between the
/// Client and Agent was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _balance The amount of tokens owed by the Client to the Agent.
/// @param _msg_sig The balance message signed by the Client or Agent (depends on _type).
/// @param _type true - extract from BalanceProofSignature signed by Client,
/// false - extract from ClosingSignature signed by Agent
/// @return Address of the balance proof signer.
function extractSignature(
address _address,
uint32 _open_block_number,
bytes32 _offering_hash,
uint64 _balance,
bytes memory _msg_sig,
bool _type)
public
view
returns (address)
{
// The hashed strings should be kept in sync with this function's parameters
// (variable names and types).
bytes32 message_hash =
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",
keccak256(abi.encodePacked(
_type ? 'Privatix: sender balance proof signature' : 'Privatix: receiver closing signature',
_address,
_open_block_number,
_offering_hash,
_balance,
address(this)
))
));
// Derive address from signature
address signer = ECVerify.ecverify(message_hash, _msg_sig);
return signer;
}
/// @notice Returns the unique channel identifier used in the contract.
/// @param _client_address The address of Client that sends tokens.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _open_block_number The block number at which a channel between the
/// Client and Agent was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @return Unique channel identifier.
function getKey(
address _client_address,
address _agent_address,
uint32 _open_block_number,
bytes32 _offering_hash)
public
pure
returns (bytes32 data)
{
return keccak256(abi.encodePacked(_client_address, _agent_address, _open_block_number, _offering_hash));
}
/*
* Private functions
*/
/// @notice Increases available service offering supply.
/// @param _agent_address The address of Agent that created service offering.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @return True in both case, when Service Offering still active or already deactivated.
function increaseOfferingSupply(address _agent_address, bytes32 _offering_hash)
private
returns (bool)
{
require(service_offering_s[_offering_hash].current_supply < service_offering_s[_offering_hash].max_supply);
// Verify that Agent owns this offering
require(service_offering_s[_offering_hash].agent_address == _agent_address);
// saving gas, as no need to update state
if(service_offering_s[_offering_hash].update_block_number == 0) return true;
service_offering_s[_offering_hash].current_supply = service_offering_s[_offering_hash].current_supply+1;
return true;
}
/// @notice Decreases available service offering supply.
/// @param _agent_address The address of Agent that created service offering.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
function decreaseOfferingSupply(address _agent_address, bytes32 _offering_hash)
private
{
require(service_offering_s[_offering_hash].update_block_number > 0);
require(service_offering_s[_offering_hash].agent_address == _agent_address);
require(service_offering_s[_offering_hash].current_supply > 0); // test I5
service_offering_s[_offering_hash].current_supply = service_offering_s[_offering_hash].current_supply-1;
}
/// @dev Creates a new channel between a Client and a Agent.
/// @param _client_address The address of Client that sends tokens.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _deposit The amount of tokens that the Client escrows.
function createChannelPrivate(address _client_address,
address _agent_address,
bytes32 _offering_hash,
uint64 _deposit) private {
require(_deposit <= channel_deposit_bugbounty_limit);
uint32 open_block_number = uint32(block.number);
// Create unique identifier from sender, receiver and current block number
bytes32 key = getKey(_client_address, _agent_address, open_block_number, _offering_hash);
require(channels[key].deposit == 0);
require(channels[key].open_block_number == 0);
require(closing_requests[key].settle_block_number == 0);
// Store channel information
channels[key] = Channel({deposit: _deposit, open_block_number: open_block_number});
}
/// @dev Updates internal balance Structures when the sender adds tokens to the channel.
/// @param _client_address The address that sends tokens.
/// @param _agent_address The address that receives tokens.
/// @param _open_block_number The block number at which a channel between the
/// sender and receiver was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _added_deposit The added token deposit with which the current deposit is increased.
function updateInternalBalanceStructs(
address _client_address,
address _agent_address,
uint32 _open_block_number,
bytes32 _offering_hash,
uint64 _added_deposit)
private
{
require(_added_deposit > 0);
require(_open_block_number > 0);
bytes32 key = getKey(_client_address, _agent_address, _open_block_number, _offering_hash);
require(channels[key].deposit > 0);
require(closing_requests[key].settle_block_number == 0);
require(channels[key].deposit + _added_deposit <= channel_deposit_bugbounty_limit);
channels[key].deposit += _added_deposit;
assert(channels[key].deposit > _added_deposit);
emit LogChannelToppedUp(_agent_address, _client_address, _offering_hash, _open_block_number, _added_deposit); // test E2
}
/// @dev Deletes the channel and settles by transferring the balance to the Agent
/// and the rest of the deposit back to the Client.
/// @param _client_address The address of Client that sends tokens.
/// @param _agent_address The address of Agent that receives tokens.
/// @param _open_block_number The block number at which a channel between the
/// sender and receiver was created.
/// @param _offering_hash Service Offering hash that uniquely identifies it.
/// @param _balance The amount of tokens owed by the sender to the receiver.
function settleChannel(
address _client_address,
address _agent_address,
uint32 _open_block_number,
bytes32 _offering_hash,
uint64 _balance)
private
{
bytes32 key = getKey(_client_address, _agent_address, _open_block_number, _offering_hash);
Channel memory channel = channels[key];
require(channel.open_block_number > 0);
require(_balance <= channel.deposit);
// Remove closed channel structures
// channel.open_block_number will become 0
delete channels[key];
delete closing_requests[key];
require(increaseOfferingSupply(_agent_address, _offering_hash));
// Send _balance to the receiver, as it is always <= deposit
uint64 fee = 0;
if(network_fee > 0) {
fee = (_balance/100000)*network_fee; // it's safe because network_fee can't be more than 10000
internal_balances[network_fee_address] = internal_balances[network_fee_address].add(fee);
_balance -= fee;
}
internal_balances[_agent_address] = internal_balances[_agent_address].add(_balance);
// Send deposit - balance back to Client
internal_balances[_client_address] = internal_balances[_client_address].add(channel.deposit - _balance - fee); // I4 test
}
/*
* Internal functions
*/
/// @dev Check if a contract exists.
/// @param _contract The address of the contract to check for.
/// @return True if a contract exists, false otherwise
function addressHasCode(address _contract) private view returns (bool) {
uint size;
assembly {
size := extcodesize(_contract)
}
return size > 0;
}
}
pragma solidity 0.5.8;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath64 {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint64 a, uint64 b) internal pure returns (uint64) {
if (a == 0) {
return 0;
}
uint64 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint64 a, uint64 b) internal pure returns (uint64) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint64 a, uint64 b) internal pure returns (uint64) {
uint64 c = a + b;
assert(c >= a);
return c;
}
}
| @notice Transfers tokens from internal balance to PTC ERC20 token. @param _value Token amount to return. | function returnBalanceERC20(uint64 _value) external {
require(token.transfer(msg.sender, _value));
}
| 13,134,731 | [
1,
1429,
18881,
2430,
628,
2713,
11013,
358,
453,
15988,
4232,
39,
3462,
1147,
18,
225,
389,
1132,
3155,
3844,
358,
327,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
327,
13937,
654,
39,
3462,
12,
11890,
1105,
389,
1132,
13,
3903,
288,
203,
1377,
2583,
12,
2316,
18,
13866,
12,
3576,
18,
15330,
16,
389,
1132,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/80001/0x2B25bbBB48438d9E43d9B7Cf7692A0a72D746497/sources/_thirdweb-dev/contracts/extension/Staking20.sol | stake token , staker - totalRewardedTokens | function _calculateTotalRewardedTokens() internal view returns (uint256) {
uint256 totalRewardedTokens = 0;
for (uint256 i = 0; i < stakersArray.length; i++) {
address staker = stakersArray[i];
uint256 rewardedTokens = _availableRewards(staker);
totalRewardedTokens += rewardedTokens;
}
return totalRewardedTokens;
}
| 5,690,829 | [
1,
334,
911,
225,
1147,
269,
384,
6388,
300,
2078,
17631,
17212,
5157,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
915,
389,
11162,
5269,
17631,
17212,
5157,
1435,
2713,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
565,
2254,
5034,
2078,
17631,
17212,
5157,
273,
374,
31,
203,
565,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
384,
581,
414,
1076,
18,
2469,
31,
277,
27245,
288,
203,
3639,
1758,
384,
6388,
273,
384,
581,
414,
1076,
63,
77,
15533,
203,
3639,
2254,
5034,
283,
11804,
5157,
273,
389,
5699,
17631,
14727,
12,
334,
6388,
1769,
203,
3639,
2078,
17631,
17212,
5157,
1011,
283,
11804,
5157,
31,
203,
565,
289,
203,
565,
327,
2078,
17631,
17212,
5157,
31,
203,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.23;
// ----------------------------------------------------------------------------
// 'buckycoin' CROWDSALE token contract
//
// Deployed to : 0xf4bea2e58380ea34dcb45c4957af56cbce32a943
// Symbol : BUC
// Name : buckycoin Token
// Total supply: 940000000
// Decimals : 18
//
// POWERED BY BUCKY HOUSE.
//
// (c) by Team @ BUCKYHOUSE 2018.
// ----------------------------------------------------------------------------
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b;
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 constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded
to a wallet
* as they arrive.
*/
contract token { function transfer(address receiver, uint amount){ } }
contract Crowdsale {
using SafeMath for uint256;
// uint256 durationInMinutes;
// address where funds are collected
address public wallet;
// token address
address public addressOfTokenUsedAsReward;
uint256 public price = 1000;
uint256 public bonusPercent = 20;
uint256 public referralBonusPercent = 5;
token tokenReward;
// mapping (address => uint) public contributions;
// mapping(address => bool) public whitelist;
mapping (address => uint) public bonuses;
mapping (address => uint) public bonusUnlockTime;
// start and end timestamps where investments are allowed (both inclusive)
// uint256 public startTime;
// uint256 public endTime;
// amount of raised money in wei
uint256 public weiRaised;
uint256 public tokensSold;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale() {
//You will change this to your wallet where you need the ETH
wallet = 0x965A2a21C60252C09E5e2872b8d3088424c4f58A;
// durationInMinutes = _durationInMinutes;
//Here will come the checksum address we got
addressOfTokenUsedAsReward = 0xF86C2C4c7Dd79Ba0480eBbEbd096F51311Cfb952;
tokenReward = token(addressOfTokenUsedAsReward);
}
bool public started = true;
function startSale() {
require(msg.sender == wallet);
started = true;
}
function stopSale() {
require(msg.sender == wallet);
started = false;
}
function setPrice(uint256 _price) {
require(msg.sender == wallet);
price = _price;
}
function changeWallet(address _wallet) {
require(msg.sender == wallet);
wallet = _wallet;
}
function changeTokenReward(address _token) {
require(msg.sender==wallet);
tokenReward = token(_token);
addressOfTokenUsedAsReward = _token;
}
function setBonusPercent(uint256 _bonusPercent) {
require(msg.sender == wallet);
bonusPercent = _bonusPercent;
}
function getBonus() {
address sender = msg.sender;
require(bonuses[sender] > 0);
require(bonusUnlockTime[sender]!=0 &&
now > bonusUnlockTime[sender]);
tokenReward.transfer(sender, bonuses[sender]);
bonuses[sender] = 0;
}
function setReferralBonusPercent(uint256 _referralBonusPercent) {
require(msg.sender == wallet);
referralBonusPercent = _referralBonusPercent;
}
// function whitelistAddresses(address[] _addrs){
// require(msg.sender==wallet);
// for(uint i = 0; i < _addrs.length; ++i)
// whitelist[_addrs[i]] = true;
// }
// function removeAddressesFromWhitelist(address[] _addrs){
// require(msg.sender==wallet);
// for(uint i = 0;i < _addrs.length;++i)
// whitelist[_addrs[i]] = false;
// }
// fallback function can be used to buy tokens
function () payable {
buyTokens(msg.sender, 0x0);
}
// low level token purchase function
function buyTokens(address beneficiary, address referrer) payable {
require(beneficiary != 0x0);
require(validPurchase());
// require(whitelist[beneficiary]);
uint256 weiAmount = msg.value;
// if(weiAmount < 10**16) throw;
// if(weiAmount > 50*10**18) throw;
// calculate token amount to be sent
uint256 tokens = weiAmount.mul(price);
uint256 bonusTokens = tokens.mul(bonusPercent)/100;
uint256 referralBonusTokens = tokens.mul(referralBonusPercent)/100;
// uint256 tokens = (weiAmount/10**(18-decimals)) * price;//weiamount * price
// update state
weiRaised = weiRaised.add(weiAmount);
// if(contributions[msg.sender].add(weiAmount)>10*10**18) throw;
// contributions[msg.sender] = contributions[msg.sender].add(weiAmount);
tokenReward.transfer(beneficiary, tokens);
tokensSold = tokensSold.add(tokens);
bonuses[beneficiary] = bonuses[beneficiary].add(bonusTokens);
bonusUnlockTime[beneficiary] = now.add(6*30 days);
tokensSold = tokensSold.add(bonusTokens);
if (referrer != 0x0) {
bonuses[referrer] = bonuses[referrer].add(referralBonusTokens);
bonusUnlockTime[referrer] = now.add(6*30 days);
tokensSold = tokensSold.add(referralBonusTokens);
}
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
bool withinPeriod = started;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
function withdrawTokens(uint256 _amount) {
require(msg.sender==wallet);
tokenReward.transfer(wallet,_amount);
}
} | * event for token purchase logging @param purchaser who paid for the tokens @param beneficiary who got the tokens @param value weis paid for purchase @param amount amount of tokens purchased/You will change this to your wallet where you need the ETH durationInMinutes = _durationInMinutes;Here will come the checksum address we got | function Crowdsale() {
wallet = 0x965A2a21C60252C09E5e2872b8d3088424c4f58A;
addressOfTokenUsedAsReward = 0xF86C2C4c7Dd79Ba0480eBbEbd096F51311Cfb952;
tokenReward = token(addressOfTokenUsedAsReward);
}
bool public started = true;
| 1,324,733 | [
1,
2575,
364,
1147,
23701,
2907,
225,
5405,
343,
14558,
10354,
30591,
364,
326,
2430,
225,
27641,
74,
14463,
814,
10354,
2363,
326,
2430,
225,
460,
732,
291,
30591,
364,
23701,
225,
3844,
3844,
434,
2430,
5405,
343,
8905,
19,
6225,
903,
2549,
333,
358,
3433,
9230,
1625,
1846,
1608,
326,
512,
2455,
3734,
30470,
273,
389,
8760,
30470,
31,
26715,
903,
12404,
326,
6697,
1758,
732,
2363,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
385,
492,
2377,
5349,
1435,
288,
203,
203,
565,
9230,
273,
374,
92,
29,
9222,
37,
22,
69,
5340,
39,
4848,
2947,
22,
39,
5908,
41,
25,
73,
6030,
9060,
70,
28,
72,
5082,
28,
5193,
3247,
71,
24,
74,
8204,
37,
31,
203,
565,
1758,
951,
1345,
6668,
1463,
17631,
1060,
273,
374,
16275,
5292,
39,
22,
39,
24,
71,
27,
40,
72,
7235,
38,
69,
3028,
3672,
73,
38,
70,
41,
16410,
5908,
26,
42,
25,
3437,
2499,
39,
19192,
8778,
22,
31,
203,
203,
203,
565,
1147,
17631,
1060,
273,
1147,
12,
2867,
951,
1345,
6668,
1463,
17631,
1060,
1769,
203,
225,
289,
203,
203,
225,
1426,
1071,
5746,
273,
638,
31,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/*
|| THE LEXDAO REGISTRY (TLDR) || version 0.3
DEAR MSG.SENDER(S):
/ TLDR is a project in beta.
// Please audit and use at your own risk.
/// Entry into TLDR shall not create an attorney/client relationship.
//// Likewise, TLDR should not be construed as legal advice or replacement for professional counsel.
///// STEAL THIS C0D3SL4W
|| lexDAO ||
~presented by Open, ESQ LLC_DAO~
< https://mainnet.aragon.org/#/openesquire/ >
*/
pragma solidity 0.5.9;
/***************
OPENZEPPELIN REFERENCE CONTRACTS - SafeMath, ScribeRole, ERC-20 transactional scripts
***************/
/**
* @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.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
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.
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
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.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @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];
}
}
/*
* @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;
}
}
contract ScribeRole is Context {
using Roles for Roles.Role;
event ScribeAdded(address indexed account);
event ScribeRemoved(address indexed account);
Roles.Role private _Scribes;
constructor () internal {
_addScribe(_msgSender());
}
modifier onlyScribe() {
require(isScribe(_msgSender()), "ScribeRole: caller does not have the Scribe role");
_;
}
function isScribe(address account) public view returns (bool) {
return _Scribes.has(account);
}
function renounceScribe() public {
_removeScribe(_msgSender());
}
function _addScribe(address account) internal {
_Scribes.add(account);
emit ScribeAdded(account);
}
function _removeScribe(address account) internal {
_Scribes.remove(account);
emit ScribeRemoved(account);
}
}
/**
* @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 Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @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"));
}
}
/***************
TLDR CONTRACT
***************/
contract TLDR is ScribeRole, ERC20 { // TLDR: Curated covenant & escrow scriptbase with incentivized arbitration
using SafeMath for uint256;
// lexDAO reference for lexScribe reputation governance fees (Ξ)
address payable public lexDAO;
// TLDR (LEX) ERC-20 token references
address public tldrAddress = address(this);
ERC20 tldrToken = ERC20(tldrAddress);
string public name = "TLDR";
string public symbol = "LEX";
uint8 public decimals = 18;
// counters for lexScribe lexScriptWrapper and registered DR (rdr) / DC (rdc)
uint256 public LSW; // number of lexScriptWrapper enscribed
uint256 public RDC; // number of rdc
uint256 public RDR; // number of rdr
// mapping for lexScribe reputation governance program
mapping(address => uint256) public reputation; // mapping lexScribe reputation points
mapping(address => uint256) public lastActionTimestamp; // mapping Unix timestamp of lexScribe governance actions (cooldown)
mapping(address => uint256) public lastSuperActionTimestamp; // mapping Unix timestamp of material lexScribe governance actions requiring longer cooldown (icedown)
// mapping for stored lexScript wrappers and registered digital retainers (DR / rdr)
mapping (uint256 => lexScriptWrapper) public lexScript; // mapping registered lexScript 'wet code' templates
mapping (uint256 => DC) public rdc; // mapping rdc call numbers for inspection and signature revocation
mapping (uint256 => DR) public rdr; // mapping rdr call numbers for inspection and scripted payments
struct lexScriptWrapper { // LSW: rdr lexScript templates maintained by lexScribes
address lexScribe; // lexScribe (0x) address that enscribed lexScript template into TLDR / can make subsequent edits (lexVersion)
address lexAddress; // (0x) address to receive lexScript wrapper lexFee / adjustable by associated lexScribe
string templateTerms; // lexScript template terms to wrap rdr with legal security
uint256 lexID; // number to reference in rdr to import lexScript terms
uint256 lexVersion; // version number to mark lexScribe edits
uint256 lexRate; // fixed divisible rate for lexFee in drToken per rdr payment made thereunder / e.g., 100 = 1% lexFee on rdr payDR transaction
}
struct DC { // Digital Covenant lexScript templates maintained by lexScribes
address signatory; // DC signatory (0x) address
string templateTerms; // DC templateTerms imported from referenced lexScriptWrapper
string signatureDetails; // DC may include signatory name or other supplementary info
uint256 lexID; // lexID number reference to include lexScriptWrapper for legal security
uint256 dcNumber; // DC number generated on signed covenant registration / identifies DC for signatory revocation
uint256 timeStamp; // block.timestamp ("now") of DC registration
bool revoked; // tracks signatory revocation status on DC
}
struct DR { // Digital Retainer created on lexScript terms maintained by lexScribes / data registered for escrow script
address client; // rdr client (0x) address
address provider; // provider (0x) address that receives ERC-20 payments in exchange for goods or services (deliverable)
address drToken; // ERC-20 digital token (0x) address used to transfer value on Ethereum under rdr
string deliverable; // description of deliverable retained for benefit of Ethereum payments
uint256 lexID; // lexID number reference to include lexScriptWrapper for legal security / default '1' for generalized rdr lexScript template
uint256 drNumber; // rdr number generated on DR registration / identifies rdr for payDR function calls
uint256 timeStamp; // block.timestamp ("now") of registration used to calculate retainerTermination UnixTime
uint256 retainerTermination; // termination date of rdr in UnixTime / locks payments to provider / after, remainder can be withrawn by client
uint256 deliverableRate; // rate for rdr deliverables in wei amount / 1 = 1000000000000000000
uint256 paid; // tracking amount of designated ERC-20 digital value paid under rdr in wei amount for payCap logic
uint256 payCap; // value cap limit on rdr payments in wei amount
bool confirmed; // tracks client countersignature status
bool disputed; // tracks dispute status from client or provider / if called, locks remainder of escrow rdr payments for reputable lexScribe resolution
}
constructor(string memory tldrTerms, uint256 tldrLexRate, address tldrLexAddress, address payable _lexDAO) public { // deploys TLDR contract & stores base lexScript
reputation[msg.sender] = 1; // sets TLDR summoner lexScribe reputation to '1' initial value
lexDAO = _lexDAO; // sets initial lexDAO (0x) address
LSW = LSW.add(1); // counts initial 'tldr' entry to LSW
lexScript[1] = lexScriptWrapper( // populates default '1' lexScript data for reference in LSW and rdr
msg.sender,
tldrLexAddress,
tldrTerms,
1,
0,
tldrLexRate);
}
// TLDR Contract Events
event Enscribed(uint256 indexed lexID, uint256 indexed lexVersion, address indexed lexScribe); // triggered on successful LSW creation / edits to LSW
event Signed(uint256 indexed lexID, uint256 indexed dcNumber, address indexed signatory); // triggered on successful DC creation / edits to DC
event Registered(uint256 indexed drNumber, uint256 indexed lexID, address indexed provider); // triggered on successful rdr
event Confirmed(uint256 indexed drNumber, uint256 indexed lexID, address indexed client); // triggered on successful rdr confirmation
event Paid(uint256 indexed drNumber, uint256 indexed lexID); // triggered on successful rdr payments
event Disputed(uint256 indexed drNumber); // triggered on rdr dispute
event Resolved(uint256 indexed drNumber); // triggered on successful rdr dispute resolution
/***************
TLDR GOVERNANCE FUNCTIONS
***************/
// restricts lexScribe TLDR reputation governance function calls to once per day (cooldown)
modifier cooldown() {
require(now.sub(lastActionTimestamp[msg.sender]) > 1 days); // enforces cooldown period
_;
lastActionTimestamp[msg.sender] = now; // block.timestamp, "now"
}
// restricts material lexScribe TLDR reputation staking and lexDAO governance function calls to once per 90 days (icedown)
modifier icedown() {
require(now.sub(lastSuperActionTimestamp[msg.sender]) > 90 days); // enforces icedown period
_;
lastSuperActionTimestamp[msg.sender] = now; // block.timestamp, "now"
}
// lexDAO can add new lexScribe to maintain TLDR
function addScribe(address account) public {
require(msg.sender == lexDAO);
_addScribe(account);
reputation[account] = 1;
}
// lexDAO can remove lexScribe from TLDR / slash reputation
function removeScribe(address account) public {
require(msg.sender == lexDAO);
_removeScribe(account);
reputation[account] = 0;
}
// lexDAO can update (0x) address receiving reputation governance stakes (Ξ) / maintaining lexScribe registry
function updateLexDAO(address payable newLexDAO) public {
require(msg.sender == lexDAO);
require(newLexDAO != address(0)); // program safety check / newLexDAO cannot be "0" burn address
lexDAO = newLexDAO; // updates lexDAO (0x) address
}
// lexScribes can submit ether (Ξ) value for TLDR reputation and special TLDR function access (TLDR write privileges, rdr dispute resolution role)
function submitETHreputation() payable public onlyScribe icedown {
require(msg.value == 0.1 ether); // tenth of ether (Ξ) fee for refreshing reputation in lexDAO
reputation[msg.sender] = 3; // sets / refreshes lexScribe reputation to '3' max value, 'three strikes, you're out' buffer
address(lexDAO).transfer(msg.value); // transfers ether value (Ξ) to designated lexDAO (0x) address
}
// lexScribes can burn minted LEX value for TLDR reputation
function submitLEXreputation() public onlyScribe icedown {
_burn(_msgSender(), 10000000000000000000); // 10 LEX burned
reputation[msg.sender] = 3; // sets / refreshes lexScribe reputation to '3' max value, 'three strikes, you're out' buffer
}
// public check on lexScribe reputation status
function isReputable(address x) public view returns (bool) { // returns true if lexScribe is reputable
return reputation[x] > 0;
}
// reputable lexScribes can reduce reputation within cooldown period
function reduceScribeRep(address reducedLexScribe) cooldown public {
require(isReputable(msg.sender)); // program governance check / lexScribe must be reputable
require(msg.sender != reducedLexScribe); // program governance check / cannot reduce own reputation
reputation[reducedLexScribe] = reputation[reducedLexScribe].sub(1); // reduces reputation by "1"
}
// reputable lexScribes can repair reputation within cooldown period
function repairScribeRep(address repairedLexScribe) cooldown public {
require(isReputable(msg.sender)); // program governance check / lexScribe must be reputable
require(msg.sender != repairedLexScribe); // program governance check / cannot repair own reputation
require(reputation[repairedLexScribe] < 3); // program governance check / cannot repair fully reputable lexScribe
require(reputation[repairedLexScribe] > 0); // program governance check / cannot repair disreputable lexScribe
reputation[repairedLexScribe] = reputation[repairedLexScribe].add(1); // repairs reputation by "1"
}
/***************
TLDR LEXSCRIBE FUNCTIONS
***************/
// reputable lexScribes can register lexScript legal wrappers on TLDR and program ERC-20 lexFees associated with lexID / LEX mint, "1"
function writeLexScript(string memory templateTerms, uint256 lexRate, address lexAddress) public {
require(isReputable(msg.sender)); // program governance check / lexScribe must be reputable
uint256 lexID = LSW.add(1); // reflects new lexScript value for tracking lexScript wrappers
LSW = LSW.add(1); // counts new entry to LSW
lexScript[lexID] = lexScriptWrapper( // populate lexScript data for rdr / rdc usage
msg.sender,
lexAddress,
templateTerms,
lexID,
0,
lexRate);
_mint(msg.sender, 1000000000000000000); // mints lexScribe "1" LEX for contribution to TLDR
emit Enscribed(lexID, 0, msg.sender);
}
// lexScribes can update TLDR lexScript wrappers with new templateTerms and (0x) newLexAddress / version up LSW
function editLexScript(uint256 lexID, string memory templateTerms, address lexAddress) public {
lexScriptWrapper storage lS = lexScript[lexID]; // retrieve LSW data
require(msg.sender == lS.lexScribe); // program safety check / authorization
uint256 lexVersion = lS.lexVersion.add(1); // updates lexVersion
lexScript[lexID] = lexScriptWrapper( // populates updated lexScript data for rdr / rdc usage
msg.sender,
lexAddress,
templateTerms,
lexID,
lexVersion,
lS.lexRate);
emit Enscribed(lexID, lexVersion, msg.sender);
}
/***************
TLDR MARKET FUNCTIONS
***************/
// public can sign and associate (0x) identity with lexScript digital covenant wrapper
function signDC(uint256 lexID, string memory signatureDetails) public { // sign Digital Covenant with (0x) address
require(lexID > (0)); // program safety check
require(lexID <= LSW); // program safety check
lexScriptWrapper storage lS = lexScript[lexID]; // retrieve LSW data
uint256 dcNumber = RDC.add(1); // reflects new rdc value for public inspection and signature revocation
RDC = RDC.add(1); // counts new entry to RDC
rdc[dcNumber] = DC( // populates rdc data
msg.sender,
lS.templateTerms,
signatureDetails,
lexID,
dcNumber,
now,
false);
emit Signed(lexID, dcNumber, msg.sender);
}
// registered DC signatories can revoke (0x) signature
function revokeDC(uint256 dcNumber) public { // revoke Digital Covenant signature with (0x) address
DC storage dc = rdc[dcNumber]; // retrieve rdc data
require(msg.sender == dc.signatory); // program safety check / authorization
rdc[dcNumber] = DC(// updates rdc data
msg.sender,
"Signature Revoked", // replaces Digital Covenant terms with revocation message
dc.signatureDetails,
dc.lexID,
dc.dcNumber,
now, // updates to revocation block.timestamp
true); // reflects revocation status
emit Signed(dc.lexID, dcNumber, msg.sender);
}
// goods and/or service providers can register DR with TLDR lexScript (lexID)
function registerDR( // rdr
address client,
address drToken,
string memory deliverable,
uint256 retainerDuration,
uint256 deliverableRate,
uint256 payCap,
uint256 lexID) public {
require(lexID > (0)); // program safety check
require(lexID <= LSW); // program safety check
require(deliverableRate <= payCap); // program safety check / economics
uint256 drNumber = RDR.add(1); // reflects new rdr value for inspection and escrow management
uint256 retainerTermination = now.add(retainerDuration); // rdr termination date in UnixTime, "now" block.timestamp + retainerDuration
RDR = RDR.add(1); // counts new entry to RDR
rdr[drNumber] = DR( // populate rdr data
client,
msg.sender,
drToken,
deliverable,
lexID,
drNumber,
now, // block.timestamp, "now"
retainerTermination,
deliverableRate,
0,
payCap,
false,
false);
emit Registered(drNumber, lexID, msg.sender);
}
// rdr client can confirm rdr offer script and countersign drNumber / trigger escrow deposit in approved payCap amount
function confirmDR(uint256 drNumber) public {
DR storage dr = rdr[drNumber]; // retrieve rdr data
require(dr.confirmed == false); // program safety check / status
require(now <= dr.retainerTermination); // program safety check / time
require(msg.sender == dr.client); // program safety check / authorization
dr.confirmed = true; // reflect rdr client countersignature
ERC20 drTokenERC20 = ERC20(dr.drToken);
drTokenERC20.transferFrom(msg.sender, address(this), dr.payCap); // escrows payCap amount in approved drToken into TLDR
emit Confirmed(drNumber, dr.lexID, msg.sender);
}
// rdr client can call to delegate role
function delegateDRclient(uint256 drNumber, address clientDelegate) public {
DR storage dr = rdr[drNumber]; // retrieve rdr data
require(dr.disputed == false); // program safety check / status
require(now <= dr.retainerTermination); // program safety check / time
require(msg.sender == dr.client); // program safety check / authorization
require(dr.paid < dr.payCap); // program safety check / economics
dr.client = clientDelegate; // updates rdr client address to delegate
}
// rdr parties can initiate dispute and lock escrowed remainder of rdr payCap in TLDR until resolution by reputable lexScribe
function disputeDR(uint256 drNumber) public {
DR storage dr = rdr[drNumber]; // retrieve rdr data
require(dr.confirmed == true); // program safety check / status
require(dr.disputed == false); // program safety check / status
require(now <= dr.retainerTermination); // program safety check / time
require(msg.sender == dr.client || msg.sender == dr.provider); // program safety check / authorization
require(dr.paid < dr.payCap); // program safety check / economics
dr.disputed = true; // updates rdr value to reflect dispute status, "true"
emit Disputed(drNumber);
}
// reputable lexScribe can resolve rdr dispute with division of remaining payCap amount in wei accounting for 5% fee / LEX mint, "1"
function resolveDR(uint256 drNumber, uint256 clientAward, uint256 providerAward) public {
DR storage dr = rdr[drNumber]; // retrieve rdr data
uint256 remainder = dr.payCap.sub(dr.paid); // alias remainder rdr wei amount for rdr resolution reference
uint256 resolutionFee = remainder.div(20); // calculates 5% lexScribe dispute resolution fee
require(dr.disputed == true); // program safety check / status
require(clientAward.add(providerAward) == remainder.sub(resolutionFee)); // program safety check / economics
require(msg.sender != dr.client); // program safety check / authorization / client cannot resolve own dispute as lexScribe
require(msg.sender != dr.provider); // program safety check / authorization / provider cannot resolve own dispute as lexScribe
require(isReputable(msg.sender)); // program governance check / resolving lexScribe must be reputable
require(balanceOf(msg.sender) >= 5000000000000000000); // program governance check / resolving lexScribe must have at least "5" LEX balance
ERC20 drTokenERC20 = ERC20(dr.drToken);
drTokenERC20.transfer(dr.client, clientAward); // executes ERC-20 award transfer to rdr client
drTokenERC20.transfer(dr.provider, providerAward); // executes ERC-20 award transfer to rdr provider
drTokenERC20.transfer(msg.sender, resolutionFee); // executes ERC-20 fee transfer to resolving lexScribe
_mint(msg.sender, 1000000000000000000); // mints resolving lexScribe "1" LEX for contribution to TLDR
dr.paid = dr.paid.add(remainder); // tallies remainder to paid wei amount to reflect rdr closure
emit Resolved(drNumber);
}
// client can call to pay rdr on TLDR
function payDR(uint256 drNumber) public { // releases escrowed drToken deliverableRate amount to provider (0x) address / lexFee for attached lexID lexAddress
DR storage dr = rdr[drNumber]; // retrieve rdr data
lexScriptWrapper storage lS = lexScript[dr.lexID]; // retrieve LSW data
require(dr.confirmed == true); // program safety check / status
require(dr.disputed == false); // program safety check / status
require(now <= dr.retainerTermination); // program safety check / time
require(msg.sender == dr.client); // program safety check / authorization
require(dr.paid.add(dr.deliverableRate) <= dr.payCap); // program safety check / economics
uint256 lexFee = dr.deliverableRate.div(lS.lexRate); // derives lexFee from rdr deliverableRate
ERC20 drTokenERC20 = ERC20(dr.drToken);
drTokenERC20.transfer(dr.provider, dr.deliverableRate.sub(lexFee)); // executes ERC-20 transfer to rdr provider in deliverableRate amount
drTokenERC20.transfer(lS.lexAddress, lexFee); // executes ERC-20 transfer of lexFee to (0x) lexAddress identified in lexID
dr.paid = dr.paid.add(dr.deliverableRate); // tracks total ERC-20 wei amount paid under rdr / used to calculate rdr remainder
emit Paid(drNumber, dr.lexID);
}
// client can call to withdraw rdr remainder on TLDR after termination
function withdrawRemainder(uint256 drNumber) public {
DR storage dr = rdr[drNumber]; // retrieve rdr data
require(dr.confirmed == true); // program safety check / status
require(dr.disputed == false); // program safety check / status
require(now >= dr.retainerTermination); // program safety check / time
require(msg.sender == dr.client); // program safety check / authorization
uint256 remainder = dr.payCap.sub(dr.paid); // derive rdr remainder
ERC20 drTokenERC20 = ERC20(dr.drToken);
require(remainder > 0); // program safety check / economics
drTokenERC20.transfer(dr.client, remainder); // executes ERC-20 transfer to rdr client in escrow remainder amount
dr.paid = dr.paid.add(remainder); // tallies remainder to paid wei amount to reflect rdr closure
}
} | program safety check / authorization
| require(msg.sender == lS.lexScribe); | 983,207 | [
1,
12890,
24179,
866,
342,
6093,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
202,
565,
2583,
12,
3576,
18,
15330,
422,
328,
55,
18,
4149,
1541,
1902,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x60Fa954e22c42F52E8C815a9476f339BD38AEEf7/sources/contracts/core/defi/three-x/ThreeXBatchProcessing.sol | * @notice each component has dependencies that form a path to aquire and subsequently swap out of the component. these are those dependenices @param swapPool A CurveMetaPool for trading USDC against FRAX @param curveMetaPool A CurveMetaPool that we want to deploy into yearn (D3, 3EUR) @param angleRouter The Angle Router to trade USDC against agEUR/ | struct ComponentDependencies {
CurveMetapool swapPool;
CurveMetapool curveMetaPool;
IAngleRouter angleRouter;
}
bytes32 public constant contractName = "ThreeXBatchProcessing";
BasicIssuanceModule public basicIssuanceModule;
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 outputAmount);
event ComponentDependenciesUpdated(address[] components, ComponentDependencies[] componentDependencies);
constructor(
IContractRegistry __contractRegistry,
IStaking _staking,
BatchTokens memory _mintBatchTokens,
BatchTokens memory _redeemBatchTokens,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _componentAddresses,
ComponentDependencies[] memory _componentDependencies,
IERC20[2] memory _swapToken,
ProcessingThreshold memory _processingThreshold
| 4,889,262 | [
1,
13798,
1794,
711,
5030,
716,
646,
279,
589,
358,
279,
1039,
471,
10815,
715,
7720,
596,
434,
326,
1794,
18,
4259,
854,
5348,
2447,
275,
1242,
225,
7720,
2864,
432,
22901,
2781,
2864,
364,
1284,
7459,
11836,
5528,
5314,
14583,
2501,
225,
8882,
2781,
2864,
432,
22901,
2781,
2864,
716,
732,
2545,
358,
7286,
1368,
677,
73,
1303,
261,
40,
23,
16,
890,
41,
1099,
13,
225,
5291,
8259,
1021,
24154,
9703,
358,
18542,
11836,
5528,
5314,
1737,
41,
1099,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
1958,
5435,
8053,
288,
203,
565,
22901,
12244,
438,
1371,
7720,
2864,
31,
203,
565,
22901,
12244,
438,
1371,
8882,
2781,
2864,
31,
203,
565,
467,
8467,
8259,
5291,
8259,
31,
203,
225,
289,
203,
203,
225,
1731,
1578,
1071,
5381,
6835,
461,
273,
315,
28019,
60,
4497,
7798,
14432,
203,
203,
203,
203,
225,
7651,
7568,
89,
1359,
3120,
1071,
5337,
7568,
89,
1359,
3120,
31,
203,
203,
225,
871,
5982,
426,
24903,
329,
12,
3890,
1578,
2581,
548,
16,
2254,
5034,
4580,
1345,
6275,
16,
2254,
5034,
876,
6275,
1769,
203,
225,
871,
5435,
8053,
7381,
12,
2867,
8526,
4085,
16,
5435,
8053,
8526,
1794,
8053,
1769,
203,
203,
225,
3885,
12,
203,
565,
467,
8924,
4243,
1001,
16351,
4243,
16,
203,
565,
467,
510,
6159,
389,
334,
6159,
16,
203,
565,
5982,
5157,
3778,
389,
81,
474,
4497,
5157,
16,
203,
565,
5982,
5157,
3778,
389,
266,
24903,
4497,
5157,
16,
203,
565,
7651,
7568,
89,
1359,
3120,
389,
13240,
7568,
89,
1359,
3120,
16,
203,
565,
1758,
8526,
3778,
389,
4652,
7148,
16,
203,
565,
5435,
8053,
8526,
3778,
389,
4652,
8053,
16,
203,
565,
467,
654,
39,
3462,
63,
22,
65,
3778,
389,
22270,
1345,
16,
203,
565,
19652,
7614,
3778,
389,
10632,
7614,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/5/0x204Bc468cc9333A7Aac12aC2dBe03DcCFe9f03d0/sources/contracts/protocol/interfaces/pool/IStorageAccessible.sol | @title IStorageAccessible - generic base interface that allows callers to access all internal storage. @notice See https://github.com/gnosis/util-contracts/blob/bb5fe5fb5df6d8400998094fb1b32a178a47c3a1/contracts/StorageAccessible.sol | interface IStorageAccessible {
function getStorageAt(uint256 offset, uint256 length) external view returns (bytes memory);
function getStorageSlotsAt(uint256[] memory slots) external view returns (bytes memory);
pragma solidity >=0.7.0 <0.9.0;
}
| 7,040,090 | [
1,
45,
3245,
10451,
300,
5210,
1026,
1560,
716,
5360,
19932,
358,
2006,
777,
2713,
2502,
18,
225,
2164,
2333,
2207,
6662,
18,
832,
19,
1600,
538,
291,
19,
1367,
17,
16351,
87,
19,
10721,
19,
9897,
25,
3030,
25,
19192,
25,
2180,
26,
72,
5193,
713,
2733,
3672,
11290,
19192,
21,
70,
1578,
69,
4033,
28,
69,
9462,
71,
23,
69,
21,
19,
16351,
87,
19,
3245,
10451,
18,
18281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5831,
467,
3245,
10451,
288,
203,
565,
445,
13840,
861,
12,
11890,
5034,
1384,
16,
2254,
5034,
769,
13,
3903,
1476,
1135,
261,
3890,
3778,
1769,
203,
203,
565,
445,
13840,
16266,
861,
12,
11890,
5034,
8526,
3778,
12169,
13,
3903,
1476,
1135,
261,
3890,
3778,
1769,
203,
683,
9454,
18035,
560,
1545,
20,
18,
27,
18,
20,
411,
20,
18,
29,
18,
20,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x30879A856a022a92d80A329D6AD4ce22c194a478/sources/browser/MimirToken.sol | * Intended to gather other abstract contracts and interfaces for Eris./ | abstract contract Divine is ERC20, Ownable {
constructor () ERC20( "Mimir Solutions", "MIMIR" ) {
_mint(Context._msgSender(), 10000 * 1e18 );
}
}
| 4,921,529 | [
1,
1702,
3934,
358,
11090,
1308,
8770,
20092,
471,
7349,
364,
512,
18387,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
17801,
6835,
21411,
558,
353,
4232,
39,
3462,
16,
14223,
6914,
288,
203,
203,
565,
3885,
1832,
4232,
39,
3462,
12,
315,
49,
381,
481,
348,
355,
6170,
3113,
315,
49,
3445,
7937,
6,
262,
288,
203,
3639,
389,
81,
474,
12,
1042,
6315,
3576,
12021,
9334,
12619,
380,
404,
73,
2643,
225,
11272,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
/**
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMWWWWWWWWWWWWWWWMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMWWNXXKKKKKKKXXXXKKKKKKXXNWWMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMWNXKKKKXXNWWWWMMWWWWMWWWWNXXXKKKXNWMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMWNXKKKXNWMMMMMMMMMNOdxKWMMMMMMMMWNXKKKXNWMMMMMMMMMMMMMM
MMMMMMMMMMMMMWXKKKNWMMMMMMMMMMMMNx:;;l0WMMMMMMMMMMMWNK0KXWMMMMMMMMMMMM
MMMMMMMMMMMWXKKXWMMMMMMMMMMMMMMXd:;;;;cOWMMMMMMMMMMMMMWXKKXWMMMMMMMMMM
MMMMMMMMMWNKKXWMMMMMMMMMMMMMMWKo;;col:;:kNMMMMMMMMMMMMMMWX0KNWMMMMMMMM
MMMMMMMMWX0XWMMMMMMMMMMMMMMMWOl;;oKWXkc;:dXMMMMMMMMMMMMMMMWX0XWMMMMMMM
MMMMMMMNKKNWMMMMMMMMMMMMMMMNkc;:dXMMMWOc;;oKWMMMMMMMMMMMMMMWNKKNMMMMMM
MMMMMMNKKNMMMMMMMMMMMMMMMMNx:;:xNMMMMMW0l;;l0WMMMMMMMWMMMMMMMNKKNMMMMM
MMMMMNKKNMMMMMMMMMMMMMMMMXd:;ckNMMMMMMMMKo:;cOWMMMMXkxkXWMMMMMNKKNMMMM
MMMMWK0NMMMMMMMMMMMMMMMWKo;;l0WMMMMMMMMMMXx:;:xNMMW0lccxXMMMMMMN0KWMMM
MMMMX0XWMMMMMMWWMMMMMMWOl;;oKWMMMMMMMMMMMMNkc;:dXMMNklcoKMMMMMMMX0XMMM
MMMWKKNMMWK0OkkkkkkKWNkc;:dXMMMMMMMMMMMMMMMWOl;;oKWMXdcxNMMMMMMMNKKWMM
MMMN0XWMMWNXX0OdlccdKOc;:xNMMMWXKKXNWNNNNWWMW0o;;l0WNkdKWMMMMMMMWX0NMM
MMMX0XMMMMMMMMMN0dlcdOxoONMMMMW0xdddddodxk0KNWXd:;l0Kx0WMMMMMMMMMX0XMM
MMMX0NMMMMMMMMMMWXxlcoOXWMMMMWKkolclodkKNNNNWWMNxcxOkKWMMMMMMMMMMX0XMM
MMMX0XMMMMMMMMMMMMNklclkNMMWXklccodxdodKWMMMMMMMNKOkKWMMMMMMMMMMMX0XMM
MMMN0XWMMMMMMMMMMMMNOoclxXN0occcdKX0xlco0WMMMMMMNOOXMMMMMMMMMMMMMX0NMM
MMMWKKWMMMMMMMMMMMMMW0dccoxocccdKWMWNklclONMMMMXOONMMMMMMMMMMMMMWKKWMM
MMMMX0XMMMMMMMMMMMMMMWKdcccccco0WMMMMNOoclkNWWKk0NMMMMMMMMMMMMMMX0XWMM
MMMMWKKNMMMMMMMMMMMMMMMXxlcccckNMMMMMMW0oclxK0kKWMMMMMMMMMMMMMMNKKWMMM
MMMMMN0KWMMMMMMMMMMMMMMMNklccoKWMMMMMMMWKdlcoxKWMMMMMMMMMMMMMMWK0NMMMM
MMMMMMN0KWMMMMMMMMMMMMMMMNOod0KXWMMMMMMNK0xoxXWMMMMMMMMMMMMMMWK0NMMMMM
MMMMMMMN0KNMMMMMMMMMMMMMMMWXKkll0WMMMMXdcoOKNMMMMMMMMMMMMMMMNK0NMMMMMM
MMMMMMMMNK0XWMMMMMMMMMMMMMMMNd:;cOWMWKo:;c0WMMMMMMMMMMMMMMWX0KNMMMMMMM
MMMMMMMMMWXKKNWMMMMMMMMMMMMMMXd:;cx0kl;;l0WMMMMMMMMMMMMMWNKKXWMMMMMMMM
MMMMMMMMMMMWX0KNWMMMMMMMMMMMMMNkc;;::;:oKWMMMMMMMMMMMMWNK0XWMMMMMMMMMM
MMMMMMMMMMMMMNXKKXNWMMMMMMMMMMMWOc;;;:dXMMMMMMMMMMMWNXKKXWMMMMMMMMMMMM
MMMMMMMMMMMMMMMWNKKKXNWMMMMMMMMMW0l:ckNMMMMMMMMMWNXKKKNWMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMWNXKKKXXNWWWMMMMX0KWMMMWWWNXXKKKXNWMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMWWNXXKKKKKXXXXXXXXXXKKKKXXNWWMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMWWNNNNNNNNNNNNWWWMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
---------------------- [ WPSmartContracts.com ] ----------------------
[ Blockchain Made Easy ]
|
| ERC-721 NFT Token Marketplace
|
|----------------------------
|
| Flavors
|
| > Suika v.2: Standard ERC-721 Token with Marketplace
| Supports Payment with Tokens, and royalties
|
*/
pragma solidity ^0.8.2;
/**
* @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 transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
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);
}
}
}
}
/**
* @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;
}
}
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory 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 = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.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 {}
}
/**
* @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);
}
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings 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];
}
}
}
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @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);
}
}
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @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 External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
/**
* @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 AccessControl is Context, IAccessControl, ERC165 {
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(IAccessControl).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 ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.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());
}
}
}
/**
* @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;
if (lastIndex != toDeleteIndex) {
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] = valueIndex; // Replace lastvalue's index to valueIndex
}
// 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) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// 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);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// 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))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// 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 Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
}
/**
* @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 Counters {
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;
}
}
contract ERC721Mochi is ERC721, ERC721Enumerable, ERC721URIStorage, AccessControlEnumerable, ERC721Burnable {
using Counters for Counters.Counter;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
Counters.Counter private _tokenIdCounter;
bool public anyoneCanMint;
constructor(address owner, string memory name, string memory symbol, bool _anyoneCanMint) ERC721(name, symbol) {
_setupRole(DEFAULT_ADMIN_ROLE, owner);
_setupRole(MINTER_ROLE, owner);
anyoneCanMint = _anyoneCanMint;
}
function autoMint(string memory _tokenURI, address to) public onlyMinter {
uint id;
do {
_tokenIdCounter.increment();
id = _tokenIdCounter.current();
} while(_exists(id));
_mint(to, id);
_setTokenURI(id, _tokenURI);
}
function mint(address to, uint256 tokenId) public onlyMinter {
_mint(to, tokenId);
}
function safeMint(address to, uint256 tokenId) public onlyMinter {
_safeMint(to, tokenId);
}
function isMinter(address account) public view returns (bool) {
return hasRole(MINTER_ROLE, account);
}
function safeMint(address to, uint256 tokenId, bytes memory _data) public onlyMinter {
_safeMint(to, tokenId, _data);
}
function _burn(uint256 tokenId) internal virtual override(ERC721, ERC721URIStorage) {
ERC721URIStorage._burn(tokenId);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable, AccessControlEnumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function addMinter(address account) public onlyRole(MINTER_ROLE) {
grantRole(MINTER_ROLE, account);
}
function canIMint() public view returns (bool) {
return anyoneCanMint || isMinter(msg.sender);
}
/**
* Open modifier to anyone can mint possibility
*/
modifier onlyMinter() {
string memory mensaje;
require(
canIMint(),
"MinterRole: caller does not have the Minter role"
);
_;
}
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making 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;
}
}
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
// 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) {
unchecked {
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) {
unchecked {
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) {
return a + b;
}
/**
* @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 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) {
return a * b;
}
/**
* @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.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
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) {
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) {
unchecked {
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.
*
* 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) {
unchecked {
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) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
contract EIP20 {
uint256 public totalSupply;
uint256 constant private MAX_UINT256 = 2**256 - 1;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show.
string public symbol; //An identifier: eg SBX
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
constructor(
uint256 _initialAmount,
string memory _tokenName,
uint8 _decimalUnits,
string memory _tokenSymbol
) {
balances[msg.sender] = _initialAmount; // Give the creator all initial tokens
totalSupply = _initialAmount; // Update total supply
name = _tokenName; // Set the name for display purposes
decimals = _decimalUnits; // Amount of decimals for display purposes
symbol = _tokenSymbol; // Set the symbol for display purposes
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
uint256 _allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && _allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (_allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title ERC721Suika
* ERC-721 Marketplace with tokens and royalties support
*/
contract ERC721Suika is ERC721Mochi, ReentrancyGuard {
using SafeMath for uint256;
using Address for address payable;
using Address for address;
// admin address, the owner of the marketplace
address payable admin;
address public contract_owner;
// ERC20 token to be used for payments
EIP20 public payment_token;
// commission rate is a value from 0 to 100
uint256 commissionRate;
// royalties commission rate is a value from 0 to 100
uint256 royaltiesCommissionRate;
// nft item creators list, used to pay royalties
mapping(uint256 => address) public creators;
// last price sold or auctioned
mapping(uint256 => uint256) public soldFor;
// Mapping from token ID to sell price in Ether or to bid price, depending if it is an auction or not
mapping(uint256 => uint256) public sellBidPrice;
// Mapping payment address for tokenId
mapping(uint256 => address payable) private _wallets;
event Sale(uint256 indexed tokenId, address indexed from, address indexed to, uint256 value);
event Commission(uint256 indexed tokenId, address indexed to, uint256 value, uint256 rate, uint256 total);
event Royalty(uint256 indexed tokenId, address indexed to, uint256 value, uint256 rate, uint256 total);
// Auction data
struct Auction {
// Parameters of the auction. Times are either
// absolute unix timestamps (seconds since 1970-01-01)
// or time periods in seconds.
address payable beneficiary;
uint auctionEnd;
// Current state of the auction.
address payable highestBidder;
uint highestBid;
// Set to true at the end, disallows any change
bool open;
// minimum reserve price in wei
uint256 reserve;
}
// mapping auctions for each tokenId
mapping(uint256 => Auction) public auctions;
// Events that will be fired on changes.
event Refund(address bidder, uint amount);
event HighestBidIncreased(address indexed bidder, uint amount, uint256 tokenId);
event AuctionEnded(address winner, uint amount);
event LimitSell(address indexed from, address indexed to, uint256 amount);
event LimitBuy(address indexed from, address indexed to, uint256 amount);
event MarketSell(address indexed from, address indexed to, uint256 amount);
event MarketBuy(address indexed from, address indexed to, uint256 amount);
constructor(
EIP20 _payment_token, address _owner, address payable _admin,
uint256 _commissionRate, uint256 _royaltiesCommissionRate, string memory name, string memory symbol, bool _anyoneCanMint)
ERC721Mochi(_owner, name, symbol, _anyoneCanMint)
{
admin = _admin;
contract_owner = _owner;
require(_commissionRate<=100, "ERC721Suika: Commission rate has to be between 0 and 100");
commissionRate = _commissionRate;
royaltiesCommissionRate = _royaltiesCommissionRate;
payment_token = _payment_token;
}
function canSell(uint256 tokenId) public view returns (bool) {
return (ownerOf(tokenId)==msg.sender && !auctions[tokenId].open);
}
// Sell option for a fixed price
function sell(uint256 tokenId, uint256 price, address payable wallet) public {
// onlyOwner
require(ownerOf(tokenId)==msg.sender, "ERC721Suika: Only owner can sell this item");
// cannot set a price if auction is activated
require(!auctions[tokenId].open, "ERC721Suika: Cannot sell an item which has an active auction");
// set sell price for index
sellBidPrice[tokenId] = price;
// If price is zero, means not for sale
if (price>0) {
// approve the Index to the current contract
approve(address(this), tokenId);
// set wallet payment
_wallets[tokenId] = wallet;
}
}
// simple function to return the price of a tokenId
// returns: sell price, bid price, sold price, only one can be non zero
function getPrice(uint256 tokenId) public view returns (uint256, uint256, uint256) {
if (sellBidPrice[tokenId]>0) return (sellBidPrice[tokenId], 0, 0);
if (auctions[tokenId].highestBid>0) return (0, auctions[tokenId].highestBid, 0);
return (0, 0, soldFor[tokenId]);
}
function canBuy(uint256 tokenId) public view returns (uint256) {
if (!auctions[tokenId].open && sellBidPrice[tokenId]>0 && sellBidPrice[tokenId]>0 && getApproved(tokenId) == address(this)) {
return sellBidPrice[tokenId];
} else {
return 0;
}
}
// Buy option
function buy(uint256 tokenId) public nonReentrant {
// is on sale
require(!auctions[tokenId].open && sellBidPrice[tokenId]>0, "ERC721Suika: The collectible is not for sale");
// transfer ownership
address owner = ownerOf(tokenId);
require(msg.sender!=owner, "ERC721Suika: The seller cannot buy his own collectible");
// we need to call a transferFrom from this contract, which is the one with permission to sell the NFT
callOptionalReturn(this, abi.encodeWithSelector(this.transferFrom.selector, owner, msg.sender, tokenId));
// calculate amounts
uint256 amount4admin = sellBidPrice[tokenId].mul(commissionRate).div(100);
uint256 amount4creator = sellBidPrice[tokenId].mul(royaltiesCommissionRate).div(100);
uint256 amount4owner = sellBidPrice[tokenId].sub(amount4admin).sub(amount4creator);
// to owner
require(payment_token.transferFrom(msg.sender, _wallets[tokenId], amount4owner), "Transfer failed.");
// to creator
if (amount4creator>0) {
require(payment_token.transferFrom(msg.sender, creators[tokenId], amount4creator), "Transfer failed.");
}
// to admin
if (amount4admin>0) {
require(payment_token.transferFrom(msg.sender, admin, amount4admin), "Transfer failed.");
}
emit Sale(tokenId, owner, msg.sender, sellBidPrice[tokenId]);
emit Commission(tokenId, owner, sellBidPrice[tokenId], commissionRate, amount4admin);
emit Royalty(tokenId, owner, sellBidPrice[tokenId], royaltiesCommissionRate, amount4creator);
soldFor[tokenId] = sellBidPrice[tokenId];
// close the sell
sellBidPrice[tokenId] = 0;
delete _wallets[tokenId];
}
function canAuction(uint256 tokenId) public view returns (bool) {
return (ownerOf(tokenId)==msg.sender && !auctions[tokenId].open && sellBidPrice[tokenId]==0);
}
// Instantiate an auction contract for a tokenId
function createAuction(uint256 tokenId, uint _closingTime, address payable _beneficiary, uint256 _reservePrice) public {
require(sellBidPrice[tokenId]==0, "ERC721Suika: The selected NFT is open for sale, cannot be auctioned");
require(!auctions[tokenId].open, "ERC721Suika: The selected NFT already has an auction");
require(ownerOf(tokenId)==msg.sender, "ERC721Suika: Only owner can auction this item");
auctions[tokenId].beneficiary = _beneficiary;
auctions[tokenId].auctionEnd = _closingTime;
auctions[tokenId].reserve = _reservePrice;
auctions[tokenId].open = true;
// approve the Index to the current contract
approve(address(this), tokenId);
}
function canBid(uint256 tokenId) public view returns (bool) {
if (!msg.sender.isContract() &&
auctions[tokenId].open &&
block.timestamp <= auctions[tokenId].auctionEnd &&
msg.sender != ownerOf(tokenId) &&
getApproved(tokenId) == address(this)
) {
return true;
} else {
return false;
}
}
/// Overrides minting function to keep track of item creators
function _mint(address to, uint256 tokenId) override internal {
creators[tokenId] = msg.sender;
super._mint(to, tokenId);
}
/// Bid on the auction with the value sent
/// together with this transaction.
/// The value will only be refunded if the
/// auction is not won.
function bid(uint256 tokenId, uint256 bid_value) public nonReentrant {
// Contracts cannot bid, because they can block the auction with a reentrant attack
require(!msg.sender.isContract(), "No script kiddies");
// auction has to be opened
require(auctions[tokenId].open, "No opened auction found");
// approve was lost
require(getApproved(tokenId) == address(this), "Cannot complete the auction");
// Revert the call if the bidding
// period is over.
require(
block.timestamp <= auctions[tokenId].auctionEnd,
"Auction already ended."
);
// If the bid is not higher, send the
// money back.
require(
bid_value > auctions[tokenId].highestBid,
"There already is a higher bid."
);
address owner = ownerOf(tokenId);
require(msg.sender!=owner, "ERC721Suika: The owner cannot bid his own collectible");
// return the funds to the previous bidder, if there is one
if (auctions[tokenId].highestBid>0) {
require(payment_token.transfer(auctions[tokenId].highestBidder, auctions[tokenId].highestBid), "Transfer failed.");
emit Refund(auctions[tokenId].highestBidder, auctions[tokenId].highestBid);
}
// now store the bid data
auctions[tokenId].highestBidder = payable(msg.sender);
// transfer tokens to contract
require(payment_token.transferFrom(msg.sender, address(this), bid_value), "Transfer failed.");
// register the highest bid value
auctions[tokenId].highestBid = bid_value;
emit HighestBidIncreased(msg.sender, bid_value, tokenId);
}
// anyone can execute withdraw if auction is opened and
// the bid time expired and the reserve was not met
// or
// the auction is openen but the contract is unable to transfer
function canWithdraw(uint256 tokenId) public view returns (bool) {
if (auctions[tokenId].open &&
(
(
block.timestamp >= auctions[tokenId].auctionEnd &&
auctions[tokenId].highestBid > 0 &&
auctions[tokenId].highestBid<auctions[tokenId].reserve
) ||
getApproved(tokenId) != address(this)
)
) {
return true;
} else {
return false;
}
}
/// Withdraw a bid when the auction is not finalized
function withdraw(uint256 tokenId) public nonReentrant {
require(canWithdraw(tokenId), "Conditions to withdraw are not met");
// transfer funds to highest bidder always
if (auctions[tokenId].highestBid > 0) {
require(payment_token.transfer(auctions[tokenId].highestBidder, auctions[tokenId].highestBid), "Transfer failed.");
}
// finalize the auction
delete auctions[tokenId];
}
function canFinalize(uint256 tokenId) public view returns (bool) {
if (auctions[tokenId].open &&
block.timestamp >= auctions[tokenId].auctionEnd &&
(
auctions[tokenId].highestBid>=auctions[tokenId].reserve ||
auctions[tokenId].highestBid==0
)
) {
return true;
} else {
return false;
}
}
// implement the auctionFinalize including the NFT transfer logic
function auctionFinalize(uint256 tokenId) public nonReentrant {
require(canFinalize(tokenId), "Cannot finalize");
if (auctions[tokenId].highestBid>0) {
// transfer the ownership of token to the highest bidder
address payable _highestBidder = auctions[tokenId].highestBidder;
// calculate payment amounts
uint256 amount4admin = auctions[tokenId].highestBid.mul(commissionRate).div(100);
uint256 amount4creator = auctions[tokenId].highestBid.mul(royaltiesCommissionRate).div(100);
uint256 amount4owner = auctions[tokenId].highestBid.sub(amount4admin).sub(amount4creator);
// to owner
require(payment_token.transfer(auctions[tokenId].beneficiary, amount4owner), "Transfer failed.");
// to creator
if (amount4creator>0) {
require(payment_token.transfer(creators[tokenId], amount4creator), "Transfer failed.");
}
// to admin
if (amount4admin>0) {
require(payment_token.transfer(admin, amount4admin), "Transfer failed.");
}
emit Sale(tokenId, auctions[tokenId].beneficiary, _highestBidder, auctions[tokenId].highestBid);
emit Royalty(tokenId, auctions[tokenId].beneficiary, auctions[tokenId].highestBid, royaltiesCommissionRate, amount4creator);
emit Commission(tokenId, auctions[tokenId].beneficiary, auctions[tokenId].highestBid, commissionRate, amount4admin);
// transfer ownership
address owner = ownerOf(tokenId);
// we need to call a transferFrom from this contract, which is the one with permission to sell the NFT
// transfer the NFT to the auction's highest bidder
callOptionalReturn(this, abi.encodeWithSelector(this.transferFrom.selector, owner, _highestBidder, tokenId));
soldFor[tokenId] = auctions[tokenId].highestBid;
}
emit AuctionEnded(auctions[tokenId].highestBidder, auctions[tokenId].highestBid);
// finalize the auction
delete auctions[tokenId];
}
// Bid query functions
function highestBidder(uint256 tokenId) public view returns (address payable) {
return auctions[tokenId].highestBidder;
}
function highestBid(uint256 tokenId) public view returns (uint256) {
return auctions[tokenId].highestBid;
}
/**
* @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(IERC721 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(), "SafeERC721: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC721: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC721: ERC20 operation did not succeed");
}
}
// update contract fields
function updateAdmin(address payable _admin, uint256 _commissionRate, uint256 _royaltiesCommissionRate, bool _anyoneCanMint, EIP20 _payment_token) public {
require(msg.sender==contract_owner, "Only contract owner can do this");
admin = _admin;
commissionRate = _commissionRate;
royaltiesCommissionRate = _royaltiesCommissionRate;
anyoneCanMint = _anyoneCanMint;
payment_token = _payment_token;
}
// update owner
function updateOwner(address _contract_owner) public {
require(msg.sender==contract_owner, "Only contract owner can do this");
// grant roles to new owner
_setupRole(DEFAULT_ADMIN_ROLE, _contract_owner);
_setupRole(MINTER_ROLE, _contract_owner);
// revoke roles of old owner
revokeRole(MINTER_ROLE, contract_owner);
_setupRole(DEFAULT_ADMIN_ROLE, contract_owner);
// change ownership
contract_owner = _contract_owner;
}
} | implement the auctionFinalize including the NFT transfer logic transfer the ownership of token to the highest bidder calculate payment amounts to owner to creator to admin | function auctionFinalize(uint256 tokenId) public nonReentrant {
require(canFinalize(tokenId), "Cannot finalize");
if (auctions[tokenId].highestBid>0) {
address payable _highestBidder = auctions[tokenId].highestBidder;
uint256 amount4admin = auctions[tokenId].highestBid.mul(commissionRate).div(100);
uint256 amount4creator = auctions[tokenId].highestBid.mul(royaltiesCommissionRate).div(100);
uint256 amount4owner = auctions[tokenId].highestBid.sub(amount4admin).sub(amount4creator);
require(payment_token.transfer(auctions[tokenId].beneficiary, amount4owner), "Transfer failed.");
if (amount4creator>0) {
require(payment_token.transfer(creators[tokenId], amount4creator), "Transfer failed.");
}
if (amount4admin>0) {
require(payment_token.transfer(admin, amount4admin), "Transfer failed.");
}
emit Sale(tokenId, auctions[tokenId].beneficiary, _highestBidder, auctions[tokenId].highestBid);
emit Royalty(tokenId, auctions[tokenId].beneficiary, auctions[tokenId].highestBid, royaltiesCommissionRate, amount4creator);
emit Commission(tokenId, auctions[tokenId].beneficiary, auctions[tokenId].highestBid, commissionRate, amount4admin);
soldFor[tokenId] = auctions[tokenId].highestBid;
}
emit AuctionEnded(auctions[tokenId].highestBidder, auctions[tokenId].highestBid);
}
| 1,140,432 | [
1,
10442,
326,
279,
4062,
7951,
554,
6508,
326,
423,
4464,
7412,
4058,
7412,
326,
23178,
434,
1147,
358,
326,
9742,
9949,
765,
4604,
5184,
30980,
358,
3410,
358,
11784,
358,
3981,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
279,
4062,
7951,
554,
12,
11890,
5034,
1147,
548,
13,
1071,
1661,
426,
8230,
970,
288,
203,
203,
3639,
2583,
12,
4169,
7951,
554,
12,
2316,
548,
3631,
315,
4515,
12409,
8863,
203,
203,
3639,
309,
261,
69,
4062,
87,
63,
2316,
548,
8009,
8766,
395,
17763,
34,
20,
13,
288,
203,
203,
5411,
1758,
8843,
429,
389,
8766,
395,
17763,
765,
273,
279,
4062,
87,
63,
2316,
548,
8009,
8766,
395,
17763,
765,
31,
203,
203,
5411,
2254,
5034,
3844,
24,
3666,
273,
279,
4062,
87,
63,
2316,
548,
8009,
8766,
395,
17763,
18,
16411,
12,
832,
3951,
4727,
2934,
2892,
12,
6625,
1769,
203,
5411,
2254,
5034,
3844,
24,
20394,
273,
279,
4062,
87,
63,
2316,
548,
8009,
8766,
395,
17763,
18,
16411,
12,
3800,
2390,
606,
799,
3951,
4727,
2934,
2892,
12,
6625,
1769,
203,
5411,
2254,
5034,
3844,
24,
8443,
273,
279,
4062,
87,
63,
2316,
548,
8009,
8766,
395,
17763,
18,
1717,
12,
8949,
24,
3666,
2934,
1717,
12,
8949,
24,
20394,
1769,
203,
203,
5411,
2583,
12,
9261,
67,
2316,
18,
13866,
12,
69,
4062,
87,
63,
2316,
548,
8009,
70,
4009,
74,
14463,
814,
16,
3844,
24,
8443,
3631,
315,
5912,
2535,
1199,
1769,
203,
203,
5411,
309,
261,
8949,
24,
20394,
34,
20,
13,
288,
203,
7734,
2583,
12,
9261,
67,
2316,
18,
13866,
12,
1793,
3062,
63,
2316,
548,
6487,
3844,
24,
20394,
3631,
315,
5912,
2535,
1199,
1769,
203,
5411,
289,
203,
203,
5411,
309,
261,
8949,
24,
3666,
34,
20,
13,
2
]
|
./full_match/42220/0x97AB3Ea0437Dccfedeb40d223918388943DB2c8f/sources/contracts/ACFI/strategies/ubeswap/StrategyStakingTripleRewardLP.sol | pauses deposits and withdraws all funds from third party systems. | function panic() public onlyManager {
pause();
IStakingRewards(chef).withdraw(balanceOf());
}
| 16,323,032 | [
1,
8774,
6117,
443,
917,
1282,
471,
598,
9446,
87,
777,
284,
19156,
628,
12126,
18285,
14908,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
3933,
1435,
1071,
1338,
1318,
288,
203,
565,
11722,
5621,
203,
565,
467,
510,
6159,
17631,
14727,
12,
343,
10241,
2934,
1918,
9446,
12,
12296,
951,
10663,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/4/0xf81009f8cC3117155d7Cf4969330Cf7dCeED3f28/sources/HManagementContract.sol | * @dev Removes `addr` from the the frozen list. Emits {UnFreeze} event. Requirements: - the caller must have the `WHITELIST_ROLE`. - contract must not be paused./ | function unFreeze(address addr) external virtual onlyWhitelister whenNotPaused(){
frozen[addr] = false;
emit UnFreeze(addr);
}
| 8,719,751 | [
1,
6220,
1375,
4793,
68,
628,
326,
326,
12810,
666,
18,
7377,
1282,
288,
984,
9194,
8489,
97,
871,
18,
29076,
30,
300,
326,
4894,
1297,
1240,
326,
1375,
16861,
7085,
67,
16256,
8338,
300,
6835,
1297,
486,
506,
17781,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
640,
9194,
8489,
12,
2867,
3091,
13,
3903,
5024,
1338,
2888,
305,
292,
1249,
1347,
1248,
28590,
1435,
95,
203,
3639,
12810,
63,
4793,
65,
273,
629,
31,
203,
3639,
3626,
1351,
9194,
8489,
12,
4793,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2021-03-11
*/
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
/**
* @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
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
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @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 _governance;
event GovernanceTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_governance = msgSender;
emit GovernanceTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function governance() public view returns (address) {
return _governance;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyGovernance() {
require(_governance == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferGovernance(address newOwner) internal virtual onlyGovernance {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit GovernanceTransferred(_governance, newOwner);
_governance = newOwner;
}
}
// File: contracts/strategies/StabilizeStrategyStablecoinArbV4.sol
pragma solidity ^0.6.6;
// This is iteration 3 of the strategy
// This is a strategy that takes advantage of arb opportunities for multiple stablecoins
// Users deposit various stables into the strategy and the strategy will sell into the lowest priced token
// In addition to that, the pool will earn interest in the form of aTokens from Aave
// Selling will occur via Curve and buying WETH via Sushiswap
// Half the profit earned from the sell and interest will be used to buy WETH and split it among the treasury, stakers and executor
// Half will remain as stables (in the form of aTokens)
// It will sell on withdrawals only when a non-contract calls it and certain requirements are met
// Anyone can be an executors and profit a percentage on a trade
// Gas cost is reimbursed, up to a percentage of the total WETH profit / stipend
// This strategy doesn't store stables but rather interest earning variants (aTokens)
interface StabilizeStakingPool {
function notifyRewardAmount(uint256) external;
}
interface StabilizePriceOracle {
function getPrice(address _address) external view returns (uint256);
}
interface CurvePool {
function get_dy(int128, int128, uint256) external view returns (uint256); // Get quantity estimate
function exchange(int128, int128, uint256, uint256) external; // Exchange tokens
}
interface TradeRouter {
function swapExactETHForTokens(uint, address[] calldata, address, uint) external payable returns (uint[] memory);
function swapExactTokensForTokens(uint, uint, address[] calldata, address, uint) external returns (uint[] memory);
function getAmountsOut(uint, address[] calldata) external view returns (uint[] memory); // For a value in, it calculates value out
}
interface AggregatorV3Interface {
function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
interface LendingPoolAddressesProvider {
function getLendingPool() external view returns (address);
}
interface LendingPool {
function withdraw(address, uint256, address) external returns (uint256);
function deposit(address, uint256, address, uint16) external;
}
interface StrategyVault {
function viewWETHProfit(uint256) external view returns (uint256);
function sendWETHProfit() external;
}
contract StabilizeStrategyStablecoinArbV4 is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
address public treasuryAddress; // Address of the treasury
address public stakingAddress; // Address to the STBZ staking pool
address public zsTokenAddress; // The address of the controlling zs-Token
address public strategyVaultAddress; // This strategy stores interest aTokens in separate vault
uint256 constant DIVISION_FACTOR = 100000;
uint256 public lastTradeTime;
uint256 public lastActionBalance; // Balance before last deposit, withdraw or trade
bool public daiOpenTrade = true; // If true, dai can trade openly with other tokens other than susd
uint256 public percentTradeTrigger = 90000; // 90% change in value will trigger a trade
uint256 public percentSell = 50000; // 50% of the tokens are sold to the cheapest token
uint256 public percentDepositor = 50000; // 1000 = 1%, depositors earn 50% of all gains (including interest)
uint256 public percentExecutor = 10000; // 10000 = 10% of WETH goes to executor
uint256 public percentStakers = 50000; // 50% of non-executor WETH goes to stakers, can be changed, rest goes to treasury
uint256 public minTradeSplit = 20000; // If the balance of a stablecoin is less than or equal to this, it trades the entire balance
uint256 public maxPercentStipend = 30000; // The maximum amount of WETH profit that can be allocated to the executor for gas in percent
uint256 public gasStipend = 1000000; // This is the gas units that are covered by executing a trade taken from the WETH profit
uint256 constant minGain = 1e16; // Minimum amount of stablecoin gain (about 0.01 USD) before buying WETH and splitting it
// Token information
// This strategy accepts multiple stablecoins
// DAI, USDC, USDT, sUSD
struct TokenInfo {
IERC20 token; // Reference of token
IERC20 aToken; // Reference to its aToken (Aave v2)
uint256 decimals; // Decimals of token
uint256 price; // Last price of token in USD
uint256 lastATokenBalance; // The balance the last time the interest was calculated
}
TokenInfo[] private tokenList; // An array of tokens accepted as deposits
StabilizePriceOracle private oracleContract; // A reference to the price oracle contract
// Strategy specific variables
address constant CURVE_DAI_SUSD = address(0xEB16Ae0052ed37f479f7fe63849198Df1765a733); // Curve pool for 2 tokens, asUSD, aDAI
address constant CURVE_ATOKEN_3 = address(0xDeBF20617708857ebe4F679508E7b7863a8A8EeE); // Curve pool for 3 tokens, aDAI, aUSDT, aUSDC
address constant SUSHISWAP_ROUTER = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); //Address of Sushiswap
address constant WETH_ADDRESS = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address constant GAS_ORACLE_ADDRESS = address(0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C); // Chainlink address for fast gas oracle
address constant LENDING_POOL_ADDRESS_PROVIDER = address(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5); // Provider for Aave addresses
constructor(
address _treasury,
address _staking,
address _zsToken,
StabilizePriceOracle _oracle
) public {
treasuryAddress = _treasury;
stakingAddress = _staking;
zsTokenAddress = _zsToken;
oracleContract = _oracle;
setupWithdrawTokens();
}
// Initialization functions
function setupWithdrawTokens() internal {
// Start with DAI
IERC20 _token = IERC20(address(0x6B175474E89094C44Da98b954EedeAC495271d0F));
IERC20 _aToken = IERC20(address(0x028171bCA77440897B824Ca71D1c56caC55b68A3)); // aDAI
tokenList.push(
TokenInfo({
token: _token,
aToken: _aToken,
decimals: _token.decimals(), // Aave tokens share decimals with normal tokens
price: 1e18,
lastATokenBalance: 0
})
);
// USDC
_token = IERC20(address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48));
_aToken = IERC20(address(0xBcca60bB61934080951369a648Fb03DF4F96263C)); // aUSDC
tokenList.push(
TokenInfo({
token: _token,
aToken: _aToken,
decimals: _token.decimals(),
price: 1e18,
lastATokenBalance: 0
})
);
// USDT
_token = IERC20(address(0xdAC17F958D2ee523a2206206994597C13D831ec7));
_aToken = IERC20(address(0x3Ed3B47Dd13EC9a98b44e6204A523E766B225811)); // aUSDT
tokenList.push(
TokenInfo({
token: _token,
aToken: _aToken,
decimals: _token.decimals(),
price: 1e18,
lastATokenBalance: 0
})
);
// sUSD
_token = IERC20(address(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51));
_aToken = IERC20(address(0x6C5024Cd4F8A59110119C56f8933403A539555EB)); //aSUSD
tokenList.push(
TokenInfo({
token: _token,
aToken: _aToken,
decimals: _token.decimals(),
price: 1e18,
lastATokenBalance: 0
})
);
}
// Modifier
modifier onlyZSToken() {
require(zsTokenAddress == _msgSender(), "Call not sent from the zs-Token");
_;
}
// Read functions
function rewardTokensCount() external view returns (uint256) {
return tokenList.length;
}
function rewardTokenAddress(uint256 _pos) external view returns (address) {
require(_pos < tokenList.length,"No token at that position");
return address(tokenList[_pos].token);
}
function balanceWithInterest() public view returns (uint256) {
return getNormalizedTotalBalance(address(this)); // This will return the total balance including interest gained
}
function balance() public view returns (uint256) {
// This excludes balance that is expected to go to the vault after interest calculation
uint256 _interestBalance = balanceWithInterest();
if(lastActionBalance < _interestBalance){
return lastActionBalance.add(_interestBalance.sub(lastActionBalance).mul(percentDepositor).div(DIVISION_FACTOR));
}else{
return _interestBalance;
}
}
function getNormalizedTotalBalance(address _address) public view returns (uint256) {
// Get the balance of the atokens+tokens at this address
uint256 _balance = 0;
uint256 _length = tokenList.length;
for(uint256 i = 0; i < _length; i++){
uint256 _bal = tokenList[i].aToken.balanceOf(_address).add(tokenList[i].token.balanceOf(_address));
_bal = _bal.mul(1e18).div(10**tokenList[i].decimals);
_balance = _balance.add(_bal); // This has been normalized to 1e18 decimals
}
return _balance;
}
function withdrawTokenReserves() public view returns (address, uint256) {
// This function will return the address and amount of the token with the lowest price
uint256 length = tokenList.length;
uint256 targetID = 0;
uint256 targetPrice = 0;
for(uint256 i = 0; i < length; i++){
if(tokenList[i].aToken.balanceOf(address(this)) > 0){
uint256 _price = tokenList[i].price;
if(targetPrice == 0 || _price <= targetPrice){
targetPrice = _price;
targetID = i;
}
}
}
if(targetPrice > 0){
return (address(tokenList[targetID].token), tokenList[targetID].aToken.balanceOf(address(this)));
}else{
return (address(0), 0); // No balance
}
}
// Write functions
function enter() external onlyZSToken {
deposit(false);
}
function exit() external onlyZSToken {
// The ZS token vault is removing all tokens from this strategy
withdraw(_msgSender(),1,1, false);
}
function deposit(bool nonContract) public onlyZSToken {
// Only the ZS token can call the function
// First the interest earned since the last call will be calculated
// Some will sent to a strategy vault to be later processed when it becomes large enough
calculateAndStoreInterest(); // This function will also call an update to lastATokenBalance
// Then convert deposited stablecoins into their aToken equivalents and updates lastATokenBalance
convertAllToAaveTokens();
// No trading is performed on deposit
if(nonContract == true){}
lastActionBalance = balanceWithInterest(); // This action balance represents pool post stablecoin deposit
}
function withdraw(address _depositor, uint256 _share, uint256 _total, bool nonContract) public onlyZSToken returns (uint256) {
require(balanceWithInterest() > 0, "There are no tokens in this strategy");
// First the interest earned since the last call will be calculated and sent to vault
calculateAndStoreInterest();
// This is in case there are some leftover raw tokens
convertAllToAaveTokens();
if(nonContract == true){
if(_share > _total.mul(percentTradeTrigger).div(DIVISION_FACTOR)){
checkAndSwapTokens(address(0)); // This will also not call calculateAndHold due to 0 address
}
}
uint256 withdrawAmount = 0;
uint256 _balance = balanceWithInterest();
if(_share < _total){
uint256 _myBalance = _balance.mul(_share).div(_total);
withdrawPerPrice(_depositor, _myBalance, false); // This will withdraw based on token price
withdrawAmount = _myBalance;
}else{
// We are all shares, transfer all
withdrawPerPrice(_depositor, _balance, true);
withdrawAmount = _balance;
}
lastActionBalance = balanceWithInterest();
return withdrawAmount;
}
// Get price from chainlink oracle
function updateTokenPrices() internal {
uint256 length = tokenList.length;
for(uint256 i = 0; i < length; i++){
uint256 price = oracleContract.getPrice(address(tokenList[i].token));
if(price > 0){
tokenList[i].price = price;
}
}
}
// This will withdraw the tokens from the contract based on their price, from lowest price to highest
function withdrawPerPrice(address _receiver, uint256 _withdrawAmount, bool _takeAll) internal {
uint256 length = tokenList.length;
uint256 _balance = 0;
if(_takeAll == true){
// We will empty out the strategy
for(uint256 i = 0; i < length; i++){
_balance = tokenList[i].aToken.balanceOf(address(this));
if(_balance > 0){
// Convert the entire a tokens to token
convertFromAToken(i, _balance);
tokenList[i].lastATokenBalance = tokenList[i].aToken.balanceOf(address(this));
}
_balance = tokenList[i].token.balanceOf(address(this));
if(_balance > 0){
// Now send the normal token back
tokenList[i].token.safeTransfer(_receiver, _balance);
}
}
return;
}
bool[4] memory done;
uint256 targetID = 0;
uint256 targetPrice = 0;
updateTokenPrices(); // Update the prices based on an off-chain Oracle
for(uint256 i = 0; i < length; i++){
targetPrice = 0; // Reset the target price
// Find the lowest priced token to withdraw
for(uint256 i2 = 0; i2 < length; i2++){
if(done[i2] == false){
uint256 _price = tokenList[i2].price;
if(targetPrice == 0 || _price <= targetPrice){
targetPrice = _price;
targetID = i2;
}
}
}
done[targetID] = true;
// Determine the balance left
uint256 _normalizedBalance = tokenList[targetID].aToken.balanceOf(address(this)).mul(1e18).div(10**tokenList[targetID].decimals);
if(_normalizedBalance <= _withdrawAmount){
// Withdraw the entire balance of this token
if(_normalizedBalance > 0){
_withdrawAmount = _withdrawAmount.sub(_normalizedBalance);
_balance = tokenList[targetID].aToken.balanceOf(address(this));
convertFromAToken(targetID, _balance);
tokenList[targetID].lastATokenBalance = tokenList[targetID].aToken.balanceOf(address(this));
tokenList[targetID].token.safeTransfer(_receiver, _balance);
}
}else{
// Withdraw a partial amount of this token
if(_withdrawAmount > 0){
// Convert the withdraw amount to the token's decimal amount
_balance = _withdrawAmount.mul(10**tokenList[targetID].decimals).div(1e18);
_withdrawAmount = 0;
convertFromAToken(targetID, _balance);
tokenList[targetID].lastATokenBalance = tokenList[targetID].aToken.balanceOf(address(this));
tokenList[targetID].token.safeTransfer(_receiver, _balance);
}
break; // Nothing more to withdraw
}
}
}
function convertFromAToken(uint256 _id, uint256 amount) internal {
// This will take the aToken and convert it to main token to be used for whatever
// It will require that the amount returned is greater than or equal to amount requested
uint256 _balance = tokenList[_id].token.balanceOf(address(this));
LendingPool lender = LendingPool(LendingPoolAddressesProvider(LENDING_POOL_ADDRESS_PROVIDER).getLendingPool()); // Load the lending pool
tokenList[_id].aToken.safeApprove(address(lender), 0);
tokenList[_id].aToken.safeApprove(address(lender), amount);
lender.withdraw(address(tokenList[_id].token), amount, address(this));
require(amount >= tokenList[_id].token.balanceOf(address(this)).sub(_balance), "Aave failed to withdraw the proper balance");
}
function convertToAToken(uint256 _id, uint256 amount) internal {
// This will take the token and convert it to atoken to be used for whatever
// It will require that the amount returned is greater than or equal to amount requested
uint256 _balance = tokenList[_id].aToken.balanceOf(address(this));
LendingPool lender = LendingPool(LendingPoolAddressesProvider(LENDING_POOL_ADDRESS_PROVIDER).getLendingPool()); // Load the lending pool
tokenList[_id].token.safeApprove(address(lender), 0);
tokenList[_id].token.safeApprove(address(lender), amount);
lender.deposit(address(tokenList[_id].token), amount, address(this), 0);
require(amount >= tokenList[_id].aToken.balanceOf(address(this)).sub(_balance), "Aave failed to return proper amount of aTokens");
}
function convertAllToAaveTokens() internal {
// Convert stables to interest earning variants
uint256 length = tokenList.length;
uint256 _balance = 0;
for(uint256 i = 0; i < length; i++){
_balance = tokenList[i].token.balanceOf(address(this));
if(_balance > 0){
// Convert the entire token to a token
convertToAToken(i, _balance);
}
// Now update its balance
tokenList[i].lastATokenBalance = tokenList[i].aToken.balanceOf(address(this));
}
}
function simulateExchange(address _inputToken, address _outputToken, uint256 _amount) internal view returns (uint256) {
if(_outputToken != WETH_ADDRESS){
// When not selling for WETH, we are only dealing with aTokens
// aSUSD only can buy and sell for aDAI due to gas costs of deployment and loops
// 0 - aDAI, 1 - aUSDC, 2 - aUSDT, 3 - aSUSD
uint256 inputID = 0;
uint256 outputID = 0;
uint256 length = tokenList.length;
for(uint256 i = 0; i < length; i++){
if(_inputToken == address(tokenList[i].aToken)){
inputID = i;
}
if(_outputToken == address(tokenList[i].aToken)){
outputID = i;
}
}
if(inputID == outputID){return 0;}
if(inputID == 3 || outputID == 3){
// Just 1 pool
int128 inCurveID = 0; // aDAI in
int128 outCurveID = 0; // aDAI out
if(inputID == 3) {inCurveID = 1;} // aUSDT in
if(outputID == 3){outCurveID = 1;} // aUSDC out
CurvePool pool = CurvePool(CURVE_DAI_SUSD);
_amount = pool.get_dy(inCurveID, outCurveID, _amount);
return _amount;
}else{
// Just 1 pool
int128 inCurveID = 0; // aDAI in
int128 outCurveID = 0; // aDAI out
if(inputID == 1) {inCurveID = 1;} // aUSDC in
if(inputID == 2) {inCurveID = 2;} // aUSDT in
if(outputID == 1){outCurveID = 1;} // aUSDC out
if(outputID == 2){outCurveID = 2;} // aUSDT out
CurvePool pool = CurvePool(CURVE_ATOKEN_3);
_amount = pool.get_dy(inCurveID, outCurveID, _amount);
return _amount;
}
}else{
// Simple Sushiswap route
// When selling for WETH, we must have already converted aToken to token
// All stables have liquid path to WETH
TradeRouter router = TradeRouter(SUSHISWAP_ROUTER);
address[] memory path = new address[](2);
path[0] = _inputToken;
path[1] = WETH_ADDRESS;
uint256[] memory estimates = router.getAmountsOut(_amount, path);
_amount = estimates[estimates.length - 1];
return _amount;
}
}
function exchange(address _inputToken, address _outputToken, uint256 _amount) internal {
if(_outputToken != WETH_ADDRESS){
// When not selling for WETH, we are only dealing with aTokens
// aSUSD only can buy and sell for aDAI
// 0 - aDAI, 1 - aUSDC, 2 - aUSDT, 3 - aSUSD
uint256 inputID = 0;
uint256 outputID = 0;
uint256 length = tokenList.length;
for(uint256 i = 0; i < length; i++){
if(_inputToken == address(tokenList[i].aToken)){
inputID = i;
}
if(_outputToken == address(tokenList[i].aToken)){
outputID = i;
}
}
if(inputID == outputID){return;}
if(inputID == 3 || outputID == 3){
// We are dealing with aSUSD
int128 inCurveID = 0; // aDAI in
int128 outCurveID = 0; // aDAI out
if(inputID == 3) {inCurveID = 1;} // aUSDT in
if(outputID == 3){outCurveID = 1;} // aUSDC out
CurvePool pool = CurvePool(CURVE_DAI_SUSD);
IERC20(_inputToken).safeApprove(CURVE_DAI_SUSD, 0);
IERC20(_inputToken).safeApprove(CURVE_DAI_SUSD, _amount);
pool.exchange(inCurveID, outCurveID, _amount, 1);
return;
}else{
// Just 1 pool
int128 inCurveID = 0; // DAI in
int128 outCurveID = 0; // DAI out
if(inputID == 1) {inCurveID = 1;} // USDC in
if(inputID == 2) {inCurveID = 2;} // USDT in
if(outputID == 1){outCurveID = 1;} // USDC out
if(outputID == 2){outCurveID = 2;} // USDT out
CurvePool pool = CurvePool(CURVE_ATOKEN_3);
IERC20(_inputToken).safeApprove(CURVE_ATOKEN_3, 0);
IERC20(_inputToken).safeApprove(CURVE_ATOKEN_3, _amount);
pool.exchange(inCurveID, outCurveID, _amount, 1);
return;
}
}else{
// Simple Sushiswap route
// When selling for WETH, we must have already converted aToken to token
// All stables have liquid path to WETH
TradeRouter router = TradeRouter(SUSHISWAP_ROUTER);
address[] memory path = new address[](2);
path[0] = _inputToken;
path[1] = WETH_ADDRESS;
IERC20(_inputToken).safeApprove(SUSHISWAP_ROUTER, 0);
IERC20(_inputToken).safeApprove(SUSHISWAP_ROUTER, _amount);
router.swapExactTokensForTokens(_amount, 1, path, address(this), now.add(60)); // Get WETH from token
return;
}
}
function getCheapestCurveToken() internal view returns (uint256) {
// This will give us the ID of the cheapest token in the pool
// And it will tell us if aDAI is higher valued than aSUSD
// We will estimate the return for trading 1000 aDAI
// The higher the return, the lower the price of the other token
uint256 targetID = 0; // Our target ID is aDAI first
uint256 aDaiAmount = uint256(1000).mul(10**tokenList[0].decimals);
uint256 highAmount = aDaiAmount;
uint256 length = tokenList.length;
for(uint256 i = 1; i < length; i++){
uint256 estimate = simulateExchange(address(tokenList[0].aToken), address(tokenList[i].aToken), aDaiAmount);
// Normalize the estimate into DAI decimals
estimate = estimate.mul(10**tokenList[0].decimals).div(10**tokenList[i].decimals);
if(estimate > highAmount){
// This token is worth less than the aDAI
highAmount = estimate;
targetID = i;
}
}
return targetID;
}
function calculateAndStoreInterest() internal {
// This function will take the difference between the last aToken balance and current and distribute some of it to the strategy vault
uint256 length = tokenList.length;
uint256 _balance = 0;
for(uint256 i = 0; i < length; i++){
_balance = tokenList[i].aToken.balanceOf(address(this)); // Get the current balance
if(_balance > tokenList[i].lastATokenBalance){
uint256 chargeableGain = _balance.sub(tokenList[i].lastATokenBalance).mul(DIVISION_FACTOR.sub(percentDepositor)).div(DIVISION_FACTOR);
// Convert the chargeableGain to token then to WETH
if(chargeableGain > 0){
// Instead of convert aTokens to weth right away, store them in a separate contract, saving gas
tokenList[i].aToken.safeTransfer(strategyVaultAddress, chargeableGain);
}
}
tokenList[i].lastATokenBalance = tokenList[i].aToken.balanceOf(address(this)); // The the current aToken amount
}
}
function calculateAndViewInterest() internal view returns (uint256) {
// This function will take the difference between the last aToken balance and current and return the calculated normalized interest gain
uint256 length = tokenList.length;
uint256 _balance = 0;
uint256 gain = 0;
for(uint256 i = 0; i < length; i++){
_balance = tokenList[i].aToken.balanceOf(address(this)); // Get the current balance
if(_balance > tokenList[i].lastATokenBalance){
// Just normalize the difference into gain
gain = gain.add(_balance.sub(tokenList[i].lastATokenBalance).mul(1e18).div(10**tokenList[i].decimals));
}
}
// Gain will be normalized and represent total gain from interest
return gain;
}
function getFastGasPrice() internal view returns (uint256) {
AggregatorV3Interface gasOracle = AggregatorV3Interface(GAS_ORACLE_ADDRESS);
( , int intGasPrice, , , ) = gasOracle.latestRoundData(); // We only want the answer
return uint256(intGasPrice);
}
function checkAndSwapTokens(address _executor) internal {
lastTradeTime = now;
if(_executor != address(0)){
calculateAndStoreInterest(); // It will send aTokens to strategy vault
}
StrategyVault vault = StrategyVault(strategyVaultAddress);
vault.sendWETHProfit(); // This will request the vault convert and send WETH to the strategy to be distributed
// Now find our target token to sell into
uint256 targetID = getCheapestCurveToken(); // Curve may have a slightly different cheap token than Chainlink
uint256 length = tokenList.length;
// Now sell all the other tokens into this token
uint256 _totalBalance = balanceWithInterest(); // Get the token balance at this contract, should increase
bool _expectIncrease = false;
for(uint256 i = 0; i < length; i++){
if(i != targetID){
uint256 localTarget = targetID;
if(i == 0){
if(daiOpenTrade == false){ // If governance prevents dai from trading for usdc and usdt
localTarget = 3; // aDAI will only sell for aSUSD as they switch often
}
}else if(i == 3){
localTarget = 0; // aSUSD will only sell for aDAI
}else{
if(localTarget == 3){continue;} // Other tokens can't buy aSUSD via curve
}
uint256 sellBalance = 0;
uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[i].decimals);
if(tokenList[i].aToken.balanceOf(address(this)) <= _minTradeTarget){
// We have a small amount of tokens to sell, so sell all of it
sellBalance = tokenList[i].aToken.balanceOf(address(this));
}else{
sellBalance = tokenList[i].aToken.balanceOf(address(this)).mul(percentSell).div(DIVISION_FACTOR);
}
uint256 minReceiveBalance = sellBalance.mul(10**tokenList[localTarget].decimals).div(10**tokenList[i].decimals); // Change to match decimals of destination
if(sellBalance > 0){
uint256 estimate = simulateExchange(address(tokenList[i].aToken), address(tokenList[localTarget].aToken), sellBalance);
if(estimate > minReceiveBalance){
_expectIncrease = true;
// We are getting a greater number of tokens, complete the exchange
exchange(address(tokenList[i].aToken), address(tokenList[localTarget].aToken), sellBalance);
}
}
}
}
uint256 _newBalance = balanceWithInterest();
if(_expectIncrease == true){
// There may be rare scenarios where we don't gain any by calling this function
require(_newBalance > _totalBalance, "Failed to gain in balance from selling tokens");
}
uint256 gain = _newBalance.sub(_totalBalance);
IERC20 weth = IERC20(WETH_ADDRESS);
uint256 _wethBalance = weth.balanceOf(address(this));
if(gain >= minGain || _wethBalance > 0){
// Minimum gain required to buy WETH is about $0.01
if(gain >= minGain){
// Buy WETH from Sushiswap with stablecoin
uint256 sellBalance = gain.mul(10**tokenList[targetID].decimals).div(1e18);
uint256 holdBalance = sellBalance.mul(percentDepositor).div(DIVISION_FACTOR);
sellBalance = sellBalance.sub(holdBalance); // We will buy WETH with this amount
if(sellBalance <= tokenList[targetID].aToken.balanceOf(address(this))){
// Convert from aToken to Token
convertFromAToken(targetID, sellBalance);
// Buy WETH
exchange(address(tokenList[targetID].token), WETH_ADDRESS, sellBalance);
_wethBalance = weth.balanceOf(address(this));
}
}
if(_wethBalance > 0){
// This is pure profit, figure out allocation
// Split the amount sent to the treasury, stakers and executor if one exists
if(_executor != address(0)){
// Executors will get a gas reimbursement in WETH and a percent of the remaining
uint256 maxGasFee = getFastGasPrice().mul(gasStipend); // This is gas stipend in wei
uint256 gasFee = tx.gasprice.mul(gasStipend); // This is gas fee requested
if(gasFee > maxGasFee){
gasFee = maxGasFee; // Gas fee cannot be greater than the maximum
}
uint256 executorAmount = gasFee;
if(gasFee >= _wethBalance.mul(maxPercentStipend).div(DIVISION_FACTOR)){
executorAmount = _wethBalance.mul(maxPercentStipend).div(DIVISION_FACTOR); // The executor will get the entire amount up to point
}else{
// Add the executor percent on top of gas fee
executorAmount = _wethBalance.sub(gasFee).mul(percentExecutor).div(DIVISION_FACTOR).add(gasFee);
}
if(executorAmount > 0){
weth.safeTransfer(_executor, executorAmount);
_wethBalance = weth.balanceOf(address(this)); // Recalculate WETH in contract
}
}
if(_wethBalance > 0){
uint256 stakersAmount = _wethBalance.mul(percentStakers).div(DIVISION_FACTOR);
uint256 treasuryAmount = _wethBalance.sub(stakersAmount);
if(treasuryAmount > 0){
weth.safeTransfer(treasuryAddress, treasuryAmount);
}
if(stakersAmount > 0){
if(stakingAddress != address(0)){
weth.safeTransfer(stakingAddress, stakersAmount);
StabilizeStakingPool(stakingAddress).notifyRewardAmount(stakersAmount);
}else{
// No staking pool selected, just send to the treasury
weth.safeTransfer(treasuryAddress, stakersAmount);
}
}
}
}
}
for(uint256 i = 0; i < length; i++){
// Now run this through again and update all the token balances to prevent being affected by interest calculator
tokenList[i].lastATokenBalance = tokenList[i].aToken.balanceOf(address(this));
}
}
function expectedProfit(bool inWETHForExecutor) external view returns (uint256) {
// This view will return the expected profit in wei units that a trading activity will have on the pool
uint256 interestGain = calculateAndViewInterest(); // Will return total gain (normalized)
if(inWETHForExecutor == true){
StrategyVault vault = StrategyVault(strategyVaultAddress);
// The first param is used to determine if interest earned will bring it over threshold
interestGain = vault.viewWETHProfit(interestGain); // Will return profit as WETH
}
// Now find our target token to sell into
uint256 targetID = getCheapestCurveToken(); // Curve may have a slightly different cheap token than Chainlink
uint256 length = tokenList.length;
// Now sell all the other tokens into this token
uint256 _normalizedGain = 0;
for(uint256 i = 0; i < length; i++){
if(i != targetID){
uint256 localTarget = targetID;
if(i == 0){
if(daiOpenTrade == false){
localTarget = 3; // aDAI will only sell for aSUSD as they switch often
}
}else if(i == 3){
localTarget = 0; // aSUSD will only sell for aDAI
}else{
if(localTarget == 3){continue;} // Other tokens can't buy aSUSD via curve
}
uint256 sellBalance = 0;
uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[i].decimals);
if(tokenList[i].aToken.balanceOf(address(this)) <= _minTradeTarget){
// We have a small amount of tokens to sell, so sell all of it
sellBalance = tokenList[i].aToken.balanceOf(address(this));
}else{
sellBalance = tokenList[i].aToken.balanceOf(address(this)).mul(percentSell).div(DIVISION_FACTOR);
}
uint256 minReceiveBalance = sellBalance.mul(10**tokenList[localTarget].decimals).div(10**tokenList[i].decimals); // Change to match decimals of destination
if(sellBalance > 0){
uint256 estimate = simulateExchange(address(tokenList[i].aToken), address(tokenList[localTarget].aToken), sellBalance);
if(estimate > minReceiveBalance){
uint256 _gain = estimate.sub(minReceiveBalance).mul(1e18).div(10**tokenList[localTarget].decimals); // Normalized gain
_normalizedGain = _normalizedGain.add(_gain);
}
}
}
}
if(inWETHForExecutor == false){
return _normalizedGain.add(interestGain);
}else{
// Calculate WETH profit
if(_normalizedGain.add(interestGain) == 0){
return 0;
}
// Calculate how much WETH the executor would make as profit
uint256 estimate = interestGain; // WETH earned from interest alone
if(_normalizedGain > 0){
uint256 sellBalance = _normalizedGain.mul(10**tokenList[targetID].decimals).div(1e18); // Convert to target decimals
uint256 holdBalance = sellBalance.mul(percentDepositor).div(DIVISION_FACTOR);
sellBalance = sellBalance.sub(holdBalance); // We will buy WETH with this amount
// Estimate output
estimate = estimate.add(simulateExchange(address(tokenList[targetID].token), WETH_ADDRESS, sellBalance));
}
// Now calculate the amount going to the executor
uint256 gasFee = getFastGasPrice().mul(gasStipend); // This is gas stipend in wei
if(gasFee >= estimate.mul(maxPercentStipend).div(DIVISION_FACTOR)){ // Max percent of total
return estimate.mul(maxPercentStipend).div(DIVISION_FACTOR); // The executor will get max percent of total
}else{
estimate = estimate.sub(gasFee); // Subtract fee from remaining balance
return estimate.mul(percentExecutor).div(DIVISION_FACTOR).add(gasFee); // Executor amount with fee added
}
}
}
function executorSwapTokens(address _executor, uint256 _minSecSinceLastTrade) external {
// Function designed to promote trading with incentive. Users get percentage of WETH from profitable trades
require(now.sub(lastTradeTime) > _minSecSinceLastTrade, "The last trade was too recent");
require(_msgSender() == tx.origin, "Contracts cannot interact with this function");
checkAndSwapTokens(_executor);
lastActionBalance = balanceWithInterest();
}
// Governance functions
function governanceSwapTokens() external onlyGovernance {
// This is function that force trade tokens at anytime. It can only be called by governance
checkAndSwapTokens(_msgSender());
lastActionBalance = balanceWithInterest();
}
function governanceToggleDaiTrade() external onlyGovernance {
// Governance can open or close dai open trade
if(daiOpenTrade == false){
daiOpenTrade = true;
}else{
daiOpenTrade = false;
}
}
// Timelock variables
uint256 private _timelockStart; // The start of the timelock to change governance variables
uint256 private _timelockType; // The function that needs to be changed
uint256 constant TIMELOCK_DURATION = 86400; // Timelock is 24 hours
// Reusable timelock variables
address private _timelock_address;
uint256[6] private _timelock_data;
modifier timelockConditionsMet(uint256 _type) {
require(_timelockType == _type, "Timelock not acquired for this function");
_timelockType = 0; // Reset the type once the timelock is used
if(balanceWithInterest() > 0){ // Timelock only applies when balance exists
require(now >= _timelockStart + TIMELOCK_DURATION, "Timelock time not met");
}
_;
}
// Change the owner of the token contract
// --------------------
function startGovernanceChange(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 1;
_timelock_address = _address;
}
function finishGovernanceChange() external onlyGovernance timelockConditionsMet(1) {
transferGovernance(_timelock_address);
}
// --------------------
// Change the treasury address
// --------------------
function startChangeTreasury(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 2;
_timelock_address = _address;
}
function finishChangeTreasury() external onlyGovernance timelockConditionsMet(2) {
treasuryAddress = _timelock_address;
}
// --------------------
// Change the staking address
// --------------------
function startChangeStakingPool(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 3;
_timelock_address = _address;
}
function finishChangeStakingPool() external onlyGovernance timelockConditionsMet(3) {
stakingAddress = _timelock_address;
}
// --------------------
// Change the zsToken address
// --------------------
function startChangeZSToken(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 4;
_timelock_address = _address;
}
function finishChangeZSToken() external onlyGovernance timelockConditionsMet(4) {
zsTokenAddress = _timelock_address;
}
// --------------------
// Change the price oracle contract used, in case of upgrades
// --------------------
function startChangePriceOracle(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 5;
_timelock_address = _address;
}
function finishChangePriceOracle() external onlyGovernance timelockConditionsMet(5) {
oracleContract = StabilizePriceOracle(_timelock_address);
}
// --------------------
// Change the trading conditions used by the strategy
// --------------------
function startChangeTradingConditions(uint256 _pTradeTrigger, uint256 _pSellPercent, uint256 _minSplit, uint256 _maxStipend, uint256 _pMaxStipend) external onlyGovernance {
// Changes a lot of trading parameters in one call
require(_pTradeTrigger <= 100000 && _pSellPercent <= 100000 && _pMaxStipend <= 100000,"Percent cannot be greater than 100%");
_timelockStart = now;
_timelockType = 6;
_timelock_data[0] = _pTradeTrigger;
_timelock_data[1] = _pSellPercent;
_timelock_data[2] = _minSplit;
_timelock_data[3] = _maxStipend;
_timelock_data[4] = _pMaxStipend;
}
function finishChangeTradingConditions() external onlyGovernance timelockConditionsMet(6) {
percentTradeTrigger = _timelock_data[0];
percentSell = _timelock_data[1];
minTradeSplit = _timelock_data[2];
gasStipend = _timelock_data[3];
maxPercentStipend = _timelock_data[4];
}
// --------------------
// Change the strategy allocations between the parties
// --------------------
function startChangeStrategyAllocations(uint256 _pDepositors, uint256 _pExecutor, uint256 _pStakers) external onlyGovernance {
// Changes strategy allocations in one call
require(_pDepositors <= 100000 && _pExecutor <= 100000 && _pStakers <= 100000,"Percent cannot be greater than 100%");
_timelockStart = now;
_timelockType = 7;
_timelock_data[0] = _pDepositors;
_timelock_data[1] = _pExecutor;
_timelock_data[2] = _pStakers;
}
function finishChangeStrategyAllocations() external onlyGovernance timelockConditionsMet(7) {
percentDepositor = _timelock_data[0];
percentExecutor = _timelock_data[1];
percentStakers = _timelock_data[2];
}
// --------------------
// Remove tokens not used in strategy from strategy
// --------------------
function startRecoverTrappedToken(address _token) external onlyGovernance {
uint256 length = tokenList.length;
// Can only remove non-strategy tokens
for(uint256 i = 0; i < length; i++){
require(_token != address(tokenList[i].token) && _token != address(tokenList[i].aToken), "Can only extract non-native tokens from strategy");
}
_timelockStart = now;
_timelockType = 8;
_timelock_address = _token;
}
function finishRecoverTrappedToken() external onlyGovernance timelockConditionsMet(8) {
IERC20 token = IERC20(_timelock_address);
token.safeTransfer(governance(), token.balanceOf(address(this)));
}
// --------------------
// Change the strategy vault address
// --------------------
function startChangeStrategyVault(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 9;
_timelock_address = _address;
}
function finishChangeStrategyVault() external onlyGovernance timelockConditionsMet(9) {
strategyVaultAddress = _timelock_address;
}
// --------------------
} | Reference to its aToken (Aave v2)
| IERC20 aToken; | 2,108,391 | [
1,
2404,
358,
2097,
279,
1345,
261,
37,
836,
331,
22,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
467,
654,
39,
3462,
279,
1345,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/100/0x4bcB3397420af3227835f053Ff79B3Fe6bbCB9ed/sources/contracts/TokenManagerHook.sol | @dev Notifies the hook about a token transfer allowing the hook to react if desired. It should return true if left unimplemented, otherwise it will prevent some functions in the TokenManager from executing successfully. @param _from The origin of the transfer @param _to The destination of the transfer @param _amount The amount of the transfer/ | function onTransfer(address _from, address _to, uint256 _amount)
external
onlyTokenManager
nonReentrant
returns (bool)
{
return _onTransfer(_from, _to, _amount);
}
| 14,266,289 | [
1,
1248,
5032,
326,
3953,
2973,
279,
1147,
7412,
15632,
326,
3953,
358,
13417,
309,
6049,
18,
2597,
1410,
327,
638,
309,
2002,
640,
21099,
16,
3541,
518,
903,
5309,
2690,
4186,
316,
326,
3155,
1318,
628,
11274,
4985,
18,
225,
389,
2080,
1021,
4026,
434,
326,
7412,
225,
389,
869,
1021,
2929,
434,
326,
7412,
225,
389,
8949,
1021,
3844,
434,
326,
7412,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
603,
5912,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
8949,
13,
203,
3639,
3903,
203,
3639,
1338,
1345,
1318,
203,
3639,
1661,
426,
8230,
970,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
327,
389,
265,
5912,
24899,
2080,
16,
389,
869,
16,
389,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x15f8Fc209A1c97a40e64Bf14C8c7D1D9c0541D0f/sources/nft.sol | get 700 eth and send to community wallet | function transferToCommunityWallet() external onlyOwner {
uint balance = accountBalance();
require(!transfered, 'Function has already been executed!');
require(balance >= 350 ether, "Balance must be equal to or greater than 350 eth");
withdraw(payable(communityWallet), 350 ether);
transfered = true;
}
| 2,747,072 | [
1,
588,
2371,
713,
13750,
471,
1366,
358,
19833,
9230,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7412,
774,
12136,
13352,
16936,
1435,
3903,
1338,
5541,
288,
203,
3639,
2254,
11013,
273,
2236,
13937,
5621,
203,
3639,
2583,
12,
5,
13866,
329,
16,
296,
2083,
711,
1818,
2118,
7120,
5124,
1769,
203,
3639,
2583,
12,
12296,
1545,
890,
3361,
225,
2437,
16,
315,
13937,
1297,
506,
3959,
358,
578,
6802,
2353,
890,
3361,
13750,
8863,
203,
203,
203,
3639,
598,
9446,
12,
10239,
429,
12,
20859,
16936,
3631,
890,
3361,
225,
2437,
1769,
203,
3639,
7412,
329,
273,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xa2Cb0dE6006Eff2B5b20719152231Bcd651BeC2f/sources/contracts/MigrateBundle.sol | * @dev Migrates a bundle between 2 ImmutableBundle contracts, this contract needs to have approval for the bundle token first @param _oldImmutableContract address of the old ImmutableBundle contract @param _newImmutableContract address of the new ImmutableBundle contract @param _oldImmutableId the id of the immutable bundle to be migrated/ immutable has to be transferred to this contract for the migration (approval needed first) withdrawing old Immutable to this address, meaning we get a regular bundle in the old NftfiBundler migrating from old NftfiBundler to new burn old bundle sending the new NftfiBundler to the new Immutable to wrap sending new immutable to user | function migrateImmutable(
address _oldImmutableContract,
address _newImmutableContract,
uint256 _oldImmutableId
) external returns (uint256) {
IERC721(_oldImmutableContract).transferFrom(msg.sender, address(this), _oldImmutableId);
address oldBundleContract = address(ImmutableBundle(_oldImmutableContract).bundler());
address newBundleContract = address(ImmutableBundle(_newImmutableContract).bundler());
uint256 oldBundleId = ImmutableBundle(_oldImmutableContract).bundleOfImmutable(_oldImmutableId);
ImmutableBundle(_oldImmutableContract).withdraw(_oldImmutableId, address(this));
uint256 newBundleId = _migrateBundle(oldBundleContract, newBundleContract, oldBundleId, address(this));
_burnBundle(oldBundleContract, oldBundleId);
IERC721(newBundleContract).safeTransferFrom(address(this), _newImmutableContract, newBundleId);
uint256 newImmutabelId = ImmutableBundle(_newImmutableContract).tokenCount();
IERC721(_newImmutableContract).safeTransferFrom(address(this), msg.sender, newImmutabelId);
emit ImmutableMigrated(newImmutabelId);
return ImmutableBundle(_newImmutableContract).tokenCount();
}
| 2,829,849 | [
1,
25483,
815,
279,
3440,
3086,
576,
7252,
3405,
20092,
16,
333,
6835,
4260,
358,
1240,
23556,
364,
326,
3440,
1147,
1122,
225,
389,
1673,
16014,
8924,
1758,
434,
326,
1592,
7252,
3405,
6835,
225,
389,
2704,
16014,
8924,
1758,
434,
326,
394,
7252,
3405,
6835,
225,
389,
1673,
16014,
548,
326,
612,
434,
326,
11732,
3440,
358,
506,
24741,
19,
11732,
711,
358,
506,
906,
4193,
358,
333,
6835,
364,
326,
6333,
261,
12908,
1125,
3577,
1122,
13,
598,
9446,
310,
1592,
7252,
358,
333,
1758,
16,
12256,
732,
336,
279,
6736,
3440,
316,
326,
1592,
423,
1222,
22056,
15405,
4196,
1776,
628,
1592,
423,
1222,
22056,
15405,
358,
394,
18305,
1592,
3440,
5431,
326,
394,
423,
1222,
22056,
15405,
358,
326,
394,
7252,
358,
2193,
5431,
394,
11732,
358,
729,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
13187,
16014,
12,
203,
3639,
1758,
389,
1673,
16014,
8924,
16,
203,
3639,
1758,
389,
2704,
16014,
8924,
16,
203,
3639,
2254,
5034,
389,
1673,
16014,
548,
203,
565,
262,
3903,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
467,
654,
39,
27,
5340,
24899,
1673,
16014,
8924,
2934,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
389,
1673,
16014,
548,
1769,
203,
3639,
1758,
1592,
3405,
8924,
273,
1758,
12,
16014,
3405,
24899,
1673,
16014,
8924,
2934,
70,
12497,
10663,
203,
3639,
1758,
394,
3405,
8924,
273,
1758,
12,
16014,
3405,
24899,
2704,
16014,
8924,
2934,
70,
12497,
10663,
203,
3639,
2254,
5034,
1592,
3405,
548,
273,
7252,
3405,
24899,
1673,
16014,
8924,
2934,
9991,
951,
16014,
24899,
1673,
16014,
548,
1769,
203,
3639,
7252,
3405,
24899,
1673,
16014,
8924,
2934,
1918,
9446,
24899,
1673,
16014,
548,
16,
1758,
12,
2211,
10019,
203,
3639,
2254,
5034,
394,
3405,
548,
273,
389,
22083,
3405,
12,
1673,
3405,
8924,
16,
394,
3405,
8924,
16,
1592,
3405,
548,
16,
1758,
12,
2211,
10019,
203,
3639,
389,
70,
321,
3405,
12,
1673,
3405,
8924,
16,
1592,
3405,
548,
1769,
203,
3639,
467,
654,
39,
27,
5340,
12,
2704,
3405,
8924,
2934,
4626,
5912,
1265,
12,
2867,
12,
2211,
3631,
389,
2704,
16014,
8924,
16,
394,
3405,
548,
1769,
203,
3639,
2254,
5034,
394,
1170,
10735,
873,
548,
273,
7252,
3405,
24899,
2704,
16014,
8924,
2934,
2316,
1380,
5621,
203,
3639,
467,
654,
39,
27,
5340,
24899,
2704,
16014,
8924,
2934,
4626,
5912,
2
]
|
pragma solidity^0.4.21;
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
function DSAuth() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public
auth
{
authority = authority_;
emit LogSetAuthority(authority);
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, this, sig);
}
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x);
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x);
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x);
}
function min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
contract DSThing is DSAuth, DSNote, DSMath {
function S(string s) internal pure returns (bytes4) {
return bytes4(keccak256(s));
}
}
contract ERC20 {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract DSTokenBase is ERC20, DSMath {
uint256 _supply;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _approvals;
function DSTokenBase(uint supply) public {
_balances[msg.sender] = supply;
_supply = supply;
}
function totalSupply() public view returns (uint) {
return _supply;
}
function balanceOf(address src) public view returns (uint) {
return _balances[src];
}
function allowance(address src, address guy) public view returns (uint) {
return _approvals[src][guy];
}
function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
if (src != msg.sender) {
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad);
}
_balances[src] = sub(_balances[src], wad);
_balances[dst] = add(_balances[dst], wad);
Transfer(src, dst, wad);
return true;
}
function approve(address guy, uint wad) public returns (bool) {
_approvals[msg.sender][guy] = wad;
Approval(msg.sender, guy, wad);
return true;
}
}
contract DSStop is DSNote, DSAuth {
bool public stopped;
modifier stoppable {
require(!stopped);
_;
}
function stop() public auth note {
stopped = true;
}
function start() public auth note {
stopped = false;
}
}
contract DSToken is DSTokenBase(0), DSStop {
string public symbol;
uint256 public decimals = 18; // standard token precision. override to customize
function DSToken(string symbol_) public {
symbol = symbol_;
}
event Mint(address indexed guy, uint wad);
event Burn(address indexed guy, uint wad);
function approve(address guy) public stoppable returns (bool) {
return super.approve(guy, uint(-1));
}
function approve(address guy, uint wad) public stoppable returns (bool) {
return super.approve(guy, wad);
}
function transferFrom(address src, address dst, uint wad)
public
stoppable
returns (bool)
{
if (src != msg.sender && _approvals[src][msg.sender] != uint(-1)) {
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad);
}
_balances[src] = sub(_balances[src], wad);
_balances[dst] = add(_balances[dst], wad);
Transfer(src, dst, wad);
return true;
}
function push(address dst, uint wad) public {
transferFrom(msg.sender, dst, wad);
}
function pull(address src, uint wad) public {
transferFrom(src, msg.sender, wad);
}
function move(address src, address dst, uint wad) public {
transferFrom(src, dst, wad);
}
function mint(uint wad) public {
mint(msg.sender, wad);
}
function burn(uint wad) public {
burn(msg.sender, wad);
}
function mint(address guy, uint wad) public auth stoppable {
_balances[guy] = add(_balances[guy], wad);
_supply = add(_supply, wad);
Mint(guy, wad);
}
function burn(address guy, uint wad) public auth stoppable {
if (guy != msg.sender && _approvals[guy][msg.sender] != uint(-1)) {
_approvals[guy][msg.sender] = sub(_approvals[guy][msg.sender], wad);
}
_balances[guy] = sub(_balances[guy], wad);
_supply = sub(_supply, wad);
Burn(guy, wad);
}
// Optional token name
string name = "";
function setName(string name_) public auth {
name = name_;
}
}
contract DSProxy is DSAuth, DSNote {
DSProxyCache public cache; // global cache for contracts
function DSProxy(address _cacheAddr) public {
require(setCache(_cacheAddr));
}
function() public payable {
}
// use the proxy to execute calldata _data on contract _code
function execute(bytes _code, bytes _data)
public
payable
returns (address target, bytes32 response)
{
target = cache.read(_code);
if (target == 0x0) {
// deploy contract & store its address in cache
target = cache.write(_code);
}
response = execute(target, _data);
}
function execute(address _target, bytes _data)
public
auth
note
payable
returns (bytes32 response)
{
require(_target != 0x0);
// call contract in current context
assembly {
let succeeded := delegatecall(sub(gas, 5000), _target, add(_data, 0x20), mload(_data), 0, 32)
response := mload(0) // load delegatecall output
switch iszero(succeeded)
case 1 {
// throw if delegatecall failed
revert(0, 0)
}
}
}
//set new cache
function setCache(address _cacheAddr)
public
auth
note
returns (bool)
{
require(_cacheAddr != 0x0); // invalid cache address
cache = DSProxyCache(_cacheAddr); // overwrite cache
return true;
}
}
// DSProxyFactory
// This factory deploys new proxy instances through build()
// Deployed proxy addresses are logged
contract DSProxyFactory {
event Created(address indexed sender, address proxy, address cache);
mapping(address=>bool) public isProxy;
DSProxyCache public cache = new DSProxyCache();
// deploys a new proxy instance
// sets owner of proxy to caller
function build() public returns (DSProxy proxy) {
proxy = build(msg.sender);
}
// deploys a new proxy instance
// sets custom owner of proxy
function build(address owner) public returns (DSProxy proxy) {
proxy = new DSProxy(cache);
Created(owner, address(proxy), address(cache));
proxy.setOwner(owner);
isProxy[proxy] = true;
}
}
// DSProxyCache
// This global cache stores addresses of contracts previously deployed
// by a proxy. This saves gas from repeat deployment of the same
// contracts and eliminates blockchain bloat.
// By default, all proxies deployed from the same factory store
// contracts in the same cache. The cache a proxy instance uses can be
// changed. The cache uses the sha3 hash of a contract's bytecode to
// lookup the address
contract DSProxyCache {
mapping(bytes32 => address) cache;
function read(bytes _code) public view returns (address) {
bytes32 hash = keccak256(_code);
return cache[hash];
}
function write(bytes _code) public returns (address target) {
assembly {
target := create(0, add(_code, 0x20), mload(_code))
switch iszero(extcodesize(target))
case 1 {
// throw if contract failed to deploy
revert(0, 0)
}
}
bytes32 hash = keccak256(_code);
cache[hash] = target;
}
}
interface DSValue {
function peek() external constant returns (bytes32, bool);
function read() external constant returns (bytes32);
}
contract TubInterface {
function mat() public view returns(uint);
// function cups(bytes32 cup) public view returns(Cup);
function ink(bytes32 cup) public view returns (uint);
function tab(bytes32 cup) public returns (uint);
function rap(bytes32 cup) public returns (uint);
//--Collateral-wrapper----------------------------------------------
// Wrapper ratio (gem per skr)
function per() public view returns (uint ray);
// Join price (gem per skr)
function ask(uint wad) public view returns (uint);
// Exit price (gem per skr)
function bid(uint wad) public view returns (uint);
function join(uint wad) public;
function exit(uint wad) public;
//--CDP-risk-indicator----------------------------------------------
// Abstracted collateral price (ref per skr)
function tag() public view returns (uint wad);
// Returns true if cup is well-collateralized
function safe(bytes32 cup) public returns (bool);
//--CDP-operations--------------------------------------------------
function open() public returns (bytes32 cup);
function give(bytes32 cup, address guy) public;
function lock(bytes32 cup, uint wad) public;
function free(bytes32 cup, uint wad) public;
function draw(bytes32 cup, uint wad) public;
function wipe(bytes32 cup, uint wad) public;
function shut(bytes32 cup) public;
function bite(bytes32 cup) public;
}
interface OtcInterface {
function sellAllAmount(address, uint, address, uint) public returns (uint);
function buyAllAmount(address, uint, address, uint) public returns (uint);
function getPayAmount(address, address, uint) public constant returns (uint);
}
interface ProxyCreationAndExecute {
function createAndSellAllAmount(
DSProxyFactory factory,
OtcInterface otc,
ERC20 payToken,
uint payAmt,
ERC20 buyToken,
uint minBuyAmt) public
returns (DSProxy proxy, uint buyAmt);
function createAndSellAllAmountPayEth(
DSProxyFactory factory,
OtcInterface otc,
ERC20 buyToken,
uint minBuyAmt) public payable returns (DSProxy proxy, uint buyAmt);
function createAndSellAllAmountBuyEth(
DSProxyFactory factory,
OtcInterface otc,
ERC20 payToken,
uint payAmt,
uint minBuyAmt) public returns (DSProxy proxy, uint wethAmt);
function createAndBuyAllAmount(
DSProxyFactory factory,
OtcInterface otc,
ERC20 buyToken,
uint buyAmt,
ERC20 payToken,
uint maxPayAmt) public returns (DSProxy proxy, uint payAmt);
function createAndBuyAllAmountPayEth(
DSProxyFactory factory,
OtcInterface otc,
ERC20 buyToken,
uint buyAmt) public payable returns (DSProxy proxy, uint wethAmt);
function createAndBuyAllAmountBuyEth(
DSProxyFactory factory,
OtcInterface otc,
uint wethAmt,
ERC20 payToken,
uint maxPayAmt) public returns (DSProxy proxy, uint payAmt);
}
interface OasisDirectInterface {
function sellAllAmount(
OtcInterface otc,
ERC20 payToken,
uint payAmt,
ERC20 buyToken,
uint minBuyAmt) public
returns (uint buyAmt);
function sellAllAmountPayEth(
OtcInterface otc,
ERC20 buyToken,
uint minBuyAmt) public payable returns (uint buyAmt);
function sellAllAmountBuyEth(
OtcInterface otc,
ERC20 payToken,
uint payAmt,
uint minBuyAmt) public returns (uint wethAmt);
function buyAllAmount(
OtcInterface otc,
ERC20 buyToken,
uint buyAmt,
ERC20 payToken,
uint maxPayAmt) public returns (uint payAmt);
function buyAllAmountPayEth(
OtcInterface otc,
ERC20 buyToken,
uint buyAmt) public payable returns (uint wethAmt);
function buyAllAmountBuyEth(
OtcInterface otc,
uint wethAmt,
ERC20 payToken,
uint maxPayAmt) public returns (uint payAmt);
}
contract WETH is ERC20 {
function deposit() public payable;
function withdraw(uint wad) public;
}
/**
A contract to help creating creating CDPs in MakerDAO's system
The motivation for this is simply to save time and automate some steps for people who
want to create CDPs often
*/
contract CDPer is DSStop, DSMath {
///Main Net\\\
uint public slippage = WAD / 50;//2%
TubInterface public tub = TubInterface(0x448a5065aeBB8E423F0896E6c5D525C040f59af3);
DSToken public dai = DSToken(0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359); // Stablecoin
DSToken public skr = DSToken(0xf53AD2c6851052A81B42133467480961B2321C09); // Abstracted collateral - PETH
WETH public gem = WETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // Underlying collateral - WETH
DSToken public gov = DSToken(0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2); // MKR Token
DSValue public feed = DSValue(0x729D19f657BD0614b4985Cf1D82531c67569197B); // Price feed
OtcInterface public otc = OtcInterface(0x14FBCA95be7e99C15Cc2996c6C9d841e54B79425);
///Kovan test net\\\
///This is the acceptable price difference when exchanging at the otc. 0.01 * 10^18 == 1% acceptable slippage
// uint public slippage = 99*10**16;//99%
// TubInterface public tub = TubInterface(0xa71937147b55Deb8a530C7229C442Fd3F31b7db2);
// DSToken public dai = DSToken(0xC4375B7De8af5a38a93548eb8453a498222C4fF2); // Stablecoin
// DSToken public skr = DSToken(0xf4d791139cE033Ad35DB2B2201435fAd668B1b64); // Abstracted collateral - PETH
// DSToken public gov = DSToken(0xAaF64BFCC32d0F15873a02163e7E500671a4ffcD); // MKR Token
// WETH public gem = WETH(0xd0A1E359811322d97991E03f863a0C30C2cF029C); // Underlying collateral - WETH
// DSValue public feed = DSValue(0xA944bd4b25C9F186A846fd5668941AA3d3B8425F); // Price feed
// OtcInterface public otc = OtcInterface(0x8cf1Cab422A0b6b554077A361f8419cDf122a9F9);
///You won't be able to create a CDP or trade less than these values
uint public minETH = WAD / 20; //0.05 ETH
uint public minDai = WAD * 50; //50 Dai
//if you recursively want to invest your CDP, this will be the target liquidation price
uint public liquidationPriceWad = 320 * WAD;
/// liquidation ratio from Maker tub (can be updated manually)
uint ratio;
function CDPer() public {
}
/**
@notice Sets all allowances and updates tub liquidation ratio
*/
function init() public auth {
gem.approve(tub, uint(-1));
skr.approve(tub, uint(-1));
dai.approve(tub, uint(-1));
gov.approve(tub, uint(-1));
gem.approve(owner, uint(-1));
skr.approve(owner, uint(-1));
dai.approve(owner, uint(-1));
gov.approve(owner, uint(-1));
dai.approve(otc, uint(-1));
gem.approve(otc, uint(-1));
tubParamUpdate();
}
/**
@notice updates tub liquidation ratio
*/
function tubParamUpdate() public auth {
ratio = tub.mat() / 10**9; //liquidation ratio
}
/**
@notice create a CDP and join with the ETH sent to this function
@dev This function wraps ETH, converts to PETH, creates a CDP, joins with the PETH created and gives the CDP to the sender. Will revert if there's not enough WETH to buy with the acceptable slippage
*/
function createAndJoinCDP() public stoppable payable returns(bytes32 id) {
require(msg.value >= minETH);
gem.deposit.value(msg.value)();
id = _openAndJoinCDPWETH(msg.value);
tub.give(id, msg.sender);
}
/**
@notice create a CDP from all the Dai in the sender's balance - needs Dai transfer approval
@dev this function will sell the Dai at otc for weth and then do the same as create and JoinCDP. Will revert if there's not enough WETH to buy with the acceptable slippage
*/
function createAndJoinCDPAllDai() public returns(bytes32 id) {
return createAndJoinCDPDai(dai.balanceOf(msg.sender));
}
/**
@notice create a CDP from the given amount of Dai in the sender's balance - needs Dai transfer approval
@dev this function will sell the Dai at otc for weth and then do the same as create and JoinCDP. Will revert if there's not enough WETH to buy with the acceptable slippage
@param amount - dai to transfer from the sender's balance (needs approval)
*/
function createAndJoinCDPDai(uint amount) public auth stoppable returns(bytes32 id) {
require(amount >= minDai);
uint price = uint(feed.read());
require(dai.transferFrom(msg.sender, this, amount));
uint bought = otc.sellAllAmount(dai, amount,
gem, wmul(WAD - slippage, wdiv(amount, price)));
id = _openAndJoinCDPWETH(bought);
tub.give(id, msg.sender);
}
/**
@notice create a CDP from the ETH sent, and then create Dai and reinvest it in the CDP until the target liquidation price is reached (or the minimum investment amount)
@dev same as openAndJoinCDP, but then draw and reinvest dai. Will revert if trades are not possible.
*/
function createCDPLeveraged() public auth stoppable payable returns(bytes32 id) {
require(msg.value >= minETH);
uint price = uint(feed.read());
gem.deposit.value(msg.value)();
id = _openAndJoinCDPWETH(msg.value);
while(_reinvest(id, price)) {}
tub.give(id, msg.sender);
}
/**
@notice create a CDP all the Dai in the sender's balance (needs approval), and then create Dai and reinvest it in the CDP until the target liquidation price is reached (or the minimum investment amount)
@dev same as openAndJoinCDPDai, but then draw and reinvest dai. Will revert if trades are not possible.
*/
function createCDPLeveragedAllDai() public returns(bytes32 id) {
return createCDPLeveragedDai(dai.balanceOf(msg.sender));
}
/**
@notice create a CDP the given amount of Dai in the sender's balance (needs approval), and then create Dai and reinvest it in the CDP until the target liquidation price is reached (or the minimum investment amount)
@dev same as openAndJoinCDPDai, but then draw and reinvest dai. Will revert if trades are not possible.
*/
function createCDPLeveragedDai(uint amount) public auth stoppable returns(bytes32 id) {
require(amount >= minDai);
uint price = uint(feed.read());
require(dai.transferFrom(msg.sender, this, amount));
uint bought = otc.sellAllAmount(dai, amount,
gem, wmul(WAD - slippage, wdiv(amount, price)));
id = _openAndJoinCDPWETH(bought);
while(_reinvest(id, price)) {}
tub.give(id, msg.sender);
}
/**
@notice Shuts a CDP and returns the value in the form of ETH. You need to give permission for the amount of debt in Dai, so that the contract will draw it from your account. You need to give the CDP to this contract before using this function. You also need to send a small amount of MKR to this contract so that the fee can be paid.
@dev this function pays all debt(from the sender's account) and fees(there must be enough MKR present on this account), then it converts PETH to WETH, and then WETH to ETH, finally it sends the balance to the sender
@param _id id of the CDP to shut - it must be given to this contract
*/
function shutForETH(uint _id) public auth stoppable {
bytes32 id = bytes32(_id);
uint debt = tub.tab(id);
if (debt > 0) {
require(dai.transferFrom(msg.sender, this, debt));
}
uint ink = tub.ink(id);// locked collateral
tub.shut(id);
uint gemBalance = tub.bid(ink);
tub.exit(ink);
gem.withdraw(min(gemBalance, gem.balanceOf(this)));
msg.sender.transfer(min(gemBalance, address(this).balance));
}
/**
@notice shuts the CDP and returns all the value in the form of Dai. You need to give permission for the amount of debt in Dai, so that the contract will draw it from your account. You need to give the CDP to this contract before using this function. You also need to send a small amount of MKR to this contract so that the fee can be paid.
@dev this function pays all debt(from the sender's account) and fees(there must be enough MKR present on this account), then it converts PETH to WETH, then trades WETH for Dai, and sends it to the sender
@param _id id of the CDP to shut - it must be given to this contract
*/
function shutForDai(uint _id) public auth stoppable {
bytes32 id = bytes32(_id);
uint debt = tub.tab(id);
if (debt > 0) {
require(dai.transferFrom(msg.sender, this, debt));
}
uint ink = tub.ink(id);// locked collateral
tub.shut(id);
uint gemBalance = tub.bid(ink);
tub.exit(ink);
uint price = uint(feed.read());
uint bought = otc.sellAllAmount(gem, min(gemBalance, gem.balanceOf(this)),
dai, wmul(WAD - slippage, wmul(gemBalance, price)));
require(dai.transfer(msg.sender, bought));
}
/**
@notice give ownership of a CDP back to the sender
@param id id of the CDP owned by this contract
*/
function giveMeCDP(uint id) public auth {
tub.give(bytes32(id), msg.sender);
}
/**
@notice transfer any token from this contract to the sender
@param token : token contract address
*/
function giveMeToken(DSToken token) public auth {
token.transfer(msg.sender, token.balanceOf(this));
}
/**
@notice transfer all ETH balance from this contract to the sender
*/
function giveMeETH() public auth {
msg.sender.transfer(address(this).balance);
}
/**
@notice transfer all ETH balance from this contract to the sender and destroy the contract. Must be stopped
*/
function destroy() public auth {
require(stopped);
selfdestruct(msg.sender);
}
/**
@notice set the acceptable price slippage for trades.
@param slip E.g: 0.01 * 10^18 == 1% acceptable slippage
*/
function setSlippage(uint slip) public auth {
require(slip < WAD);
slippage = slip;
}
/**
@notice set the target liquidation price for leveraged CDPs created
@param wad E.g. 300 * 10^18 == 300 USD target liquidation price
*/
function setLiqPrice(uint wad) public auth {
liquidationPriceWad = wad;
}
/**
@notice set the minimal ETH for trades (depends on otc)
@param wad minimal ETH to trade
*/
function setMinETH(uint wad) public auth {
minETH = wad;
}
/**
@notice set the minimal Dai for trades (depends on otc)
@param wad minimal Dai to trade
*/
function setMinDai(uint wad) public auth {
minDai = wad;
}
function setTub(TubInterface _tub) public auth {
tub = _tub;
}
function setDai(DSToken _dai) public auth {
dai = _dai;
}
function setSkr(DSToken _skr) public auth {
skr = _skr;
}
function setGov(DSToken _gov) public auth {
gov = _gov;
}
function setGem(WETH _gem) public auth {
gem = _gem;
}
function setFeed(DSValue _feed) public auth {
feed = _feed;
}
function setOTC(OtcInterface _otc) public auth {
otc = _otc;
}
function _openAndJoinCDPWETH(uint amount) internal returns(bytes32 id) {
id = tub.open();
_joinCDP(id, amount);
}
function _joinCDP(bytes32 id, uint amount) internal {
uint skRate = tub.ask(WAD);
uint valueSkr = wdiv(amount, skRate);
tub.join(valueSkr);
tub.lock(id, min(valueSkr, skr.balanceOf(this)));
}
function _reinvest(bytes32 id, uint latestPrice) internal returns(bool ok) {
// Cup memory cup = tab.cups(id);
uint debt = tub.tab(id);
uint ink = tub.ink(id);// locked collateral
uint maxInvest = wdiv(wmul(liquidationPriceWad, ink), ratio);
if(debt >= maxInvest) {
return false;
}
uint leftOver = sub(maxInvest, debt);
if(leftOver >= minDai) {
tub.draw(id, leftOver);
uint bought = otc.sellAllAmount(dai, min(leftOver, dai.balanceOf(this)),
gem, wmul(WAD - slippage, wdiv(leftOver, latestPrice)));
_joinCDP(id, bought);
return true;
} else {
return false;
}
}
}
contract CDPerFactory {
event Created(address indexed sender, address cdper);
mapping(address=>bool) public isCDPer;
// deploys a new CDPer instance
// sets owner of CDPer to caller
function build() public returns (CDPer cdper) {
cdper = build(msg.sender);
}
// deploys a new CDPer instance
// sets custom owner of CDPer
function build(address owner) public returns (CDPer cdper) {
cdper = new CDPer();
emit Created(owner, address(cdper));
cdper.setOwner(owner);
isCDPer[cdper] = true;
}
} | Abstracted collateral - PETH
| DSToken public skr = DSToken(0xf53AD2c6851052A81B42133467480961B2321C09); | 10,077,285 | [
1,
7469,
329,
4508,
2045,
287,
300,
453,
1584,
44,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
463,
882,
969,
1071,
4343,
86,
273,
463,
882,
969,
12,
20,
5841,
8643,
1880,
22,
71,
26,
7140,
2163,
9401,
37,
11861,
38,
9452,
3437,
5026,
26,
5608,
3672,
29,
9498,
38,
22,
1578,
21,
39,
5908,
1769,
282,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2021-05-14
*/
// File: @openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.6.8;
/*
* @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/GSN/Context.sol
// File: @openzeppelin/contracts/introspection/IERC165.sol
/**
* @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: @openzeppelin/contracts/token/ERC721/IERC721.sol
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// File: @openzeppelin/contracts/introspection/ERC165.sol
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract 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 virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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/Address.sol
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
/**
* @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/EnumerableMap.sol
/**
* @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: @openzeppelin/contracts/utils/Strings.sol
/**
* @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--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// File: contracts/ERC721.sol
/**
* NOTE: This file is a clone of the OpenZeppelin ERC721.sol contract. It was forked from https://github.com/OpenZeppelin/openzeppelin-contracts
* at commit 1ada3b633e5bfd9d4ffe0207d64773a11f5a7c40
*
*
* The following functions needed to be modified, prompting this clone:
* - `_tokenURIs` visibility was changed from private to internal to support updating URIs after minting
* - `_baseURI` visibiility was changed from private to internal to support fetching token URI even after the token was burned
* - `_INTERFACE_ID_ERC721_METADATA` is no longer registered as an interface because _tokenURI now returns raw content instead of a JSON file, and supports updatable URIs
* - `_approve` visibility was changed from private to internal to support EIP-2612 flavored permits and approval revocation by an approved address
*/
/**
* @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) 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 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(
owner != address(0),
"ERC721: balance query for the zero address"
);
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return
_tokenOwners.get(
tokenId,
"ERC721: owner query for nonexistent token"
);
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
// If there is no base URI, return the token URI.
if (bytes(_baseURI).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(_baseURI, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(_baseURI, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
override
returns (uint256)
{
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
override
returns (address)
{
require(
_exists(tokenId),
"ERC721: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {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 returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
returns (bool)
{
require(
_exists(tokenId),
"ERC721: operator query for nonexistent token"
);
address owner = ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {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);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(
ownerOf(tokenId) == from,
"ERC721: transfer of token that is not own"
);
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI)
internal
virtual
{
require(
_exists(tokenId),
"ERC721Metadata: URI set of nonexistent token"
);
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (!to.isContract()) {
return true;
}
bytes memory returndata =
to.functionCall(
abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
),
"ERC721: transfer to non ERC721Receiver implementer"
);
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) internal {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: contracts/ERC721Burnable.sol
/**
* NOTE: This file is a clone of the OpenZeppelin ERC721Burnable.sol contract. It was forked from https://github.com/OpenZeppelin/openzeppelin-contracts
* at commit 1ada3b633e5bfd9d4ffe0207d64773a11f5a7c40
*
* It was cloned in order to ensure it imported from the cloned ERC721.sol file. No other modifications have been made.
*/
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @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);
}
}
// File: @openzeppelin/contracts/math/Math.sol
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
/**
* @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/ReentrancyGuard.sol
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: contracts/Math.sol
pragma experimental ABIEncoderV2;
/**
* @title Math
*
* Library for non-standard Math functions
* NOTE: This file is a clone of the dydx protocol's Decimal.sol contract.
* It was forked from https://github.com/dydxprotocol/solo at commit
* 2d8454e02702fe5bc455b848556660629c3cad36. It has not been modified other than to use a
* newer solidity in the pragma to match the rest of the contract suite of this project.
*/
library MathEx {
using SafeMath for uint256;
// ============ Library Functions ============
/*
* Return target * (numerator / denominator).
*/
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
) internal pure returns (uint256) {
return target.mul(numerator).div(denominator);
}
/*
* Return target * (numerator / denominator), but rounded up.
*/
function getPartialRoundUp(
uint256 target,
uint256 numerator,
uint256 denominator
) internal pure returns (uint256) {
if (target == 0 || numerator == 0) {
// SafeMath will check for zero denominator
return SafeMath.div(0, denominator);
}
return target.mul(numerator).sub(1).div(denominator).add(1);
}
function to128(uint256 number) internal pure returns (uint128) {
uint128 result = uint128(number);
require(result == number, "Math: Unsafe cast to uint128");
return result;
}
function to96(uint256 number) internal pure returns (uint96) {
uint96 result = uint96(number);
require(result == number, "Math: Unsafe cast to uint96");
return result;
}
function to32(uint256 number) internal pure returns (uint32) {
uint32 result = uint32(number);
require(result == number, "Math: Unsafe cast to uint32");
return result;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
}
// File: contracts/Decimal.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* NOTE: This file is a clone of the dydx protocol's Decimal.sol contract. It was forked from https://github.com/dydxprotocol/solo
* at commit 2d8454e02702fe5bc455b848556660629c3cad36
*
* It has not been modified other than to use a newer solidity in the pragma to match the rest of the contract suite of this project
*/
/**
* @title Decimal
*
* Library that defines a fixed-point number with 18 decimal places.
*/
library Decimal {
using SafeMath for uint256;
// ============ Constants ============
uint256 constant BASE_POW = 18;
uint256 constant BASE = 10**BASE_POW;
// ============ Structs ============
struct D256 {
uint256 value;
}
// ============ Functions ============
function one() internal pure returns (D256 memory) {
return D256({value: BASE});
}
function onePlus(D256 memory d) internal pure returns (D256 memory) {
return D256({value: d.value.add(BASE)});
}
function mul(uint256 target, D256 memory d)
internal
pure
returns (uint256)
{
return MathEx.getPartial(target, d.value, BASE);
}
function div(uint256 target, D256 memory d)
internal
pure
returns (uint256)
{
return MathEx.getPartial(target, BASE, d.value);
}
}
// File: contracts/interfaces/IMedia.sol
//import {IMarket} from "./IMarket.sol";
/**
* @title Interface for Pxbee Protocol's Media
*/
interface IMedia {
struct EIP712Signature {
uint256 deadline;
uint8 v;
bytes32 r;
bytes32 s;
}
struct MediaData {
// A valid URI of the content represented by this token
string tokenURI;
// A SHA256 hash of the content pointed to by tokenURI
bytes32 contentHash;
}
event TokenURIUpdated(uint256 indexed _tokenId, address owner, string _uri);
/**
* @notice Mint new media for msg.sender.
*/
//function mint(MediaData calldata data, IMarket.BidShares calldata bidShares) external;
function mint(uint256 tokenId, MediaData calldata data) external;
/**
* @notice Mint new media for creator.
*/
//function mintForCreator(address creator, MediaData calldata data, IMarket.BidShares calldata bidShares) external;
function mintForCreator(address creator, uint256 tokenId, MediaData calldata data) external;
/**
* @notice EIP-712 mintWithSig method. Mints new media for a creator given a valid signature.
*/
//function mintWithSig(address creator, MediaData calldata data, IMarket.BidShares calldata bidShares, EIP712Signature calldata sig) external;
function mintWithSig(address creator, uint256 tokenId, MediaData calldata data, EIP712Signature calldata sig) external;
/**
* @notice Transfer the token with the given ID to a given address.
* Save the previous owner before the transfer, in case there is a sell-on fee.
* @dev This can only be called by the auction contract specified at deployment
*/
//function auctionTransfer(uint256 tokenId, address recipient) external;
/**
* @notice Set the ask on a piece of media
*/
//function setAsk(uint256 tokenId, IMarket.Ask calldata ask) external;
/**
* @notice Remove the ask on a piece of media
*/
//function removeAsk(uint256 tokenId) external;
/**
* @notice Set the bid on a piece of media
*/
//function setBid(uint256 tokenId, IMarket.Bid calldata bid) external;
/**
* @notice Remove the bid on a piece of media
*/
//function removeBid(uint256 tokenId) external;
//function acceptBid(uint256 tokenId, IMarket.Bid calldata bid) external;
/**
* @notice Revoke approval for a piece of media
*/
function revokeApproval(uint256 tokenId) external;
/**
* @notice Update the token URI
*/
function updateTokenURI(uint256 tokenId, string calldata tokenURI) external;
/**
* @notice EIP-712 permit method. Sets an approved spender given a valid signature.
*/
function permit(address spender, uint256 tokenId, EIP712Signature calldata sig) external;
}
// File: contracts/Media.sol
//import {IMarket} from "./interfaces/IMarket.sol";
/**
* @title A media value system, with perpetual equity to creators
* @notice This contract provides an interface to mint media with a market
* owned by the creator.
*/
contract Media is IMedia, ERC721Burnable, ReentrancyGuard {
using SafeMath for uint256;
/* *******
* Globals
* *******
*/
// Address for the market
//address public marketContract;
// Mapping from token to previous owner of the token
//mapping(uint256 => address) public previousTokenOwners;
// Mapping from token id to creator address
//mapping(uint256 => address) public tokenCreators;
// Mapping from creator address to their (enumerable) set of created tokens
//mapping(address => EnumerableSet.UintSet) private _creatorTokens;
// Mapping from token id to sha256 hash of content
mapping(uint256 => bytes32) public tokenContentHashes;
// Mapping from contentHash to bool
// mapping(bytes32 => bool) private _contentHashes;
struct tokenID {
uint256 value;
bool isValid;
}
mapping(bytes32 => tokenID) private _contentHashes;
//keccak256("Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH =
0x49ecf333e5b8c95c40fdafc95c1ad136e8914a8fb55e9dc8bb01eaa83a2df9ad;
//keccak256("MintWithSig(bytes32 contentHash,bytes32 metadataHash,uint256 creatorShare,uint256 nonce,uint256 deadline)");
//bytes32 public constant MINT_WITH_SIG_TYPEHASH =
// 0x2952e482b8e2b192305f87374d7af45dc2eafafe4f50d26a0c02e90f2fdbe14b;
//keccak256("MintWithSig(bytes32 contentHash,uint256 nonce,uint256 deadline)");
bytes32 public constant MINT_WITH_SIG_TYPEHASH =
0x7540a87a6f5a3ca71228cbcf292e92bad63a56d2f56ffabd2c53ec29c9f4671f;
// Mapping from address to token id to permit nonce
mapping(address => mapping(uint256 => uint256)) public permitNonces;
// Mapping from address to mint with sig nonce
mapping(address => uint256) public mintWithSigNonces;
/*
* 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;
/* *********
* Modifiers
* *********
*/
/**
* @notice Require that the token has not been burned and has been minted
*/
modifier onlyExistingToken(uint256 tokenId) {
require(_exists(tokenId), "Media: nonexistent token");
_;
}
/**
* @notice Require that the token has had a content hash set
*/
modifier onlyTokenWithContentHash(uint256 tokenId) {
require(
tokenContentHashes[tokenId] != 0,
"Media: token does not have hash of created content"
);
_;
}
/**
* @notice Ensure that the provided spender is the approved or the owner of
* the media for the specified tokenId
*/
modifier onlyApprovedOrOwner(address spender, uint256 tokenId) {
require(
_isApprovedOrOwner(spender, tokenId),
"Media: Only approved or owner"
);
_;
}
/**
* @notice Ensure that the provided URI is not empty
*/
modifier onlyValidURI(string memory uri) {
require(
bytes(uri).length != 0,
"Media: specified uri must be non-empty"
);
_;
}
/**
* @notice On deployment, set the market contract address and register the
* ERC721 metadata interface
*/
// constructor(address marketContractAddr) public ERC721("Pxbee", "PXBEE") {
// marketContract = marketContractAddr;
// _registerInterface(_INTERFACE_ID_ERC721_METADATA);
// }
constructor() public ERC721("Pxbee", "PXBEE") {
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
/* **************
* View Functions
* **************
*/
/**
* @notice return the URI for a particular piece of media with the specified tokenId
* @dev This function is an override of the base OZ implementation because we
* will return the tokenURI even if the media has been burned. In addition, this
* protocol does not support a base URI, so relevant conditionals are removed.
* @return the URI for a token
*/
function tokenURI(uint256 tokenId)
public
view
override
onlyExistingToken(tokenId)
returns (string memory)
{
string memory _tokenURI = _tokenURIs[tokenId];
return _tokenURI;
}
/**
* @notice get the tokenId given the content_hash if the token has been minted
* @return the tokenId of the token
*/
function getTokenIdByContentHash(bytes32 contentHash)
public
view
returns (uint256)
{
require(
_contentHashes[contentHash].isValid == true,
"This token has not been minted."
);
return _contentHashes[contentHash].value;
}
/* ****************
* Public Functions
* ****************
*/
/**
* @notice see IMedia
*/
//function mint(MediaData memory data, IMarket.BidShares memory bidShares)
function mint(uint256 tokenId, MediaData memory data)
public
override
nonReentrant
{
//_mintForCreator(msg.sender, data, bidShares);
_mintForCreator(msg.sender, tokenId, data);
}
/**
* @notice see IMedia
*/
//function mintForCreator(address creator, MediaData memory data, IMarket.BidShares memory bidShares)
function mintForCreator(address creator, uint256 tokenId, MediaData memory data)
public
override
nonReentrant
{
//_mintForCreator(creator, data, bidShares);
_mintForCreator(creator, tokenId, data);
}
/**
* @notice see IMedia
*/
function mintWithSig(
address creator,
uint256 tokenId,
MediaData memory data,
//IMarket.BidShares memory bidShares,
EIP712Signature memory sig
) public override nonReentrant {
require(
sig.deadline == 0 || sig.deadline >= block.timestamp,
"Media: mintWithSig expired"
);
bytes32 domainSeparator = _calculateDomainSeparator();
bytes32 digest =
keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
keccak256(
abi.encode(
MINT_WITH_SIG_TYPEHASH,
data.contentHash,
//bidShares.creator.value,
mintWithSigNonces[creator]++,
sig.deadline
)
)
)
);
address recoveredAddress = ecrecover(digest, sig.v, sig.r, sig.s);
require(
recoveredAddress != address(0) && creator == recoveredAddress,
"Media: Signature invalid"
);
//_mintForCreator(recoveredAddress, data, bidShares);
_mintForCreator(recoveredAddress, tokenId, data);
}
/**
* @notice see IMedia
*/
// function auctionTransfer(uint256 tokenId, address recipient)
// external
// override
// {
// require(msg.sender == marketContract, "Media: only market contract");
// previousTokenOwners[tokenId] = ownerOf(tokenId);
// _safeTransfer(ownerOf(tokenId), recipient, tokenId, "");
// }
/**
* @notice see IMedia
*/
// function setAsk(uint256 tokenId, IMarket.Ask memory ask)
// public
// override
// nonReentrant
// onlyApprovedOrOwner(msg.sender, tokenId)
// {
// IMarket(marketContract).setAsk(tokenId, ask);
// }
/**
* @notice see IMedia
*/
// function removeAsk(uint256 tokenId)
// external
// override
// nonReentrant
// onlyApprovedOrOwner(msg.sender, tokenId)
// {
// IMarket(marketContract).removeAsk(tokenId);
// }
/**
* @notice see IMedia
*/
// function setBid(uint256 tokenId, IMarket.Bid memory bid)
// public
// override
// nonReentrant
// onlyExistingToken(tokenId)
// {
// require(msg.sender == bid.bidder, "Market: Bidder must be msg sender");
// IMarket(marketContract).setBid(tokenId, bid, msg.sender);
// }
/**
* @notice see IMedia
*/
// function removeBid(uint256 tokenId)
// external
// override
// nonReentrant
// onlyExistingToken(tokenId)
// {
// IMarket(marketContract).removeBid(tokenId, msg.sender);
// }
/**
* @notice see IMedia
*/
// function acceptBid(uint256 tokenId, IMarket.Bid memory bid)
// public
// override
// nonReentrant
// onlyApprovedOrOwner(msg.sender, tokenId)
// {
// IMarket(marketContract).acceptBid(tokenId, bid);
// }
/**
* @notice Burn a token.
* @dev Only callable if the media owner is also the creator.
*/
function burn(uint256 tokenId)
public
override
nonReentrant
onlyExistingToken(tokenId)
onlyApprovedOrOwner(msg.sender, tokenId)
{
//address owner = ownerOf(tokenId);
// require(
// tokenCreators[tokenId] == owner,
// "Media: owner is not creator of media"
// );
_burn(tokenId);
}
/**
* @notice Revoke the approvals for a token. The provided `approve` function is not sufficient
* for this protocol, as it does not allow an approved address to revoke it's own approval.
* In instances where a 3rd party is interacting on a user's behalf via `permit`, they should
* revoke their approval once their task is complete as a best practice.
*/
function revokeApproval(uint256 tokenId) external override nonReentrant {
require(
msg.sender == getApproved(tokenId),
"Media: caller not approved address"
);
_approve(address(0), tokenId);
}
/**
* @notice see IMedia
* @dev only callable by approved or owner
*/
function updateTokenURI(uint256 tokenId, string calldata _tokenURI)
external
override
nonReentrant
onlyApprovedOrOwner(msg.sender, tokenId)
onlyTokenWithContentHash(tokenId)
onlyValidURI(_tokenURI)
{
_setTokenURI(tokenId, _tokenURI);
emit TokenURIUpdated(tokenId, msg.sender, _tokenURI);
}
/**
* @notice See IMedia
* @dev This method is loosely based on the permit for ERC-20 tokens in EIP-2612, but modified
* for ERC-721.
*/
function permit(
address spender,
uint256 tokenId,
EIP712Signature memory sig
) public override nonReentrant onlyExistingToken(tokenId) {
require(
sig.deadline == 0 || sig.deadline >= block.timestamp,
"Media: Permit expired"
);
require(spender != address(0), "Media: spender cannot be 0x0");
bytes32 domainSeparator = _calculateDomainSeparator();
bytes32 digest =
keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
spender,
tokenId,
permitNonces[ownerOf(tokenId)][tokenId]++,
sig.deadline
)
)
)
);
address recoveredAddress = ecrecover(digest, sig.v, sig.r, sig.s);
require(
recoveredAddress != address(0) &&
ownerOf(tokenId) == recoveredAddress,
"Media: Signature invalid"
);
_approve(spender, tokenId);
}
/* *****************
* Private Functions
* *****************
*/
/**
* @notice Creates a new token for `creator`. Its token ID will be automatically
* assigned (and available on the emitted {IERC721-Transfer} event), and the token
* URI autogenerated based on the base URI passed at construction.
*
* See {ERC721-_safeMint}.
*
* On mint, also set the sha256 hashes of the content for integrity
* checks, along with the initial URIs to point to the content. Attribute
* the token ID to the creator, mark the content hash as used, and set the bid shares for
* the media's market.
*
* Note that the content hash must be unique for future mints to prevent duplicate media.
*/
function _mintForCreator(
address creator,
uint256 tokenId,
MediaData memory data
//IMarket.BidShares memory bidShares
) internal onlyValidURI(data.tokenURI) {
require(data.contentHash != 0, "Media: content hash must be non-zero");
require(
_contentHashes[data.contentHash].isValid == false,
"Media: a token has already been created with this content hash"
);
require(
_exists(tokenId) == false,
"Media: existent tokenId"
);
_safeMint(creator, tokenId);
_setTokenContentHash(tokenId, data.contentHash);
_setTokenURI(tokenId, data.tokenURI);
//_creatorTokens[creator].add(tokenId);
_contentHashes[data.contentHash].value = tokenId;
_contentHashes[data.contentHash].isValid = true;
//tokenCreators[tokenId] = creator;
//previousTokenOwners[tokenId] = creator;
//IMarket(marketContract).setBidShares(tokenId, bidShares);
}
function _setTokenContentHash(uint256 tokenId, bytes32 contentHash)
internal
virtual
onlyExistingToken(tokenId)
{
tokenContentHashes[tokenId] = contentHash;
}
/**
* @notice Destroys `tokenId`.
* @dev We modify the OZ _burn implementation to
* maintain metadata and to remove the
* previous token owner from the piece
*/
function _burn(uint256 tokenId) internal override {
string memory _tokenURI = _tokenURIs[tokenId];
super._burn(tokenId);
if (bytes(_tokenURI).length != 0) {
_tokenURIs[tokenId] = _tokenURI;
}
//delete previousTokenOwners[tokenId];
}
/**
* @notice transfer a token and remove the ask for it.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal override {
//IMarket(marketContract).removeAsk(tokenId);
super._transfer(from, to, tokenId);
}
/**
* @dev Calculates EIP712 DOMAIN_SEPARATOR based on the current contract and chain ID.
*/
function _calculateDomainSeparator() internal view returns (bytes32) {
uint256 chainID;
/* solium-disable-next-line */
assembly {
chainID := chainid()
}
return
keccak256(
abi.encode(
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
),
keccak256(bytes("Pxbee")),
keccak256(bytes("1")),
chainID,
address(this)
)
);
}
} | * @notice get the tokenId given the content_hash if the token has been minted @return the tokenId of the token/ | function getTokenIdByContentHash(bytes32 contentHash)
public
view
returns (uint256)
{
require(
_contentHashes[contentHash].isValid == true,
"This token has not been minted."
);
return _contentHashes[contentHash].value;
}
| 10,648,537 | [
1,
588,
326,
1147,
548,
864,
326,
913,
67,
2816,
309,
326,
1147,
711,
2118,
312,
474,
329,
327,
326,
1147,
548,
434,
326,
1147,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
9162,
548,
858,
1350,
2310,
12,
3890,
1578,
913,
2310,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
2583,
12,
203,
5411,
389,
1745,
14455,
63,
1745,
2310,
8009,
26810,
422,
638,
16,
203,
5411,
315,
2503,
1147,
711,
486,
2118,
312,
474,
329,
1199,
203,
3639,
11272,
203,
3639,
327,
389,
1745,
14455,
63,
1745,
2310,
8009,
1132,
31,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.11;
contract ERC20Interface {
function totalSupply() constant returns (uint supply);
function balanceOf(address _owner) constant returns (uint balance);
function transfer(address _to, uint _value) returns (bool success);
function transferFrom(address _from, address _to, uint _value) returns (bool success);
function approve(address _spender, uint _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint remaining);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
contract DDAContract is ERC20Interface {
string public constant symbol = "DDA";
string public constant name = "DeDeAnchor";
uint8 public constant decimals = 18;
uint256 public _totalSupply = 10**26;//smallest unit is 10**-18, and total dda is 10**8
mapping (address => uint) public balances;
mapping (address => mapping (address => uint256)) public allowed;
address dedeAddress;
// ERC20 FUNCTIONS
function totalSupply() constant returns (uint totalSupply){
return _totalSupply;
}
function balanceOf(address _owner) constant returns (uint balance){
return balances[_owner];
}
function transfer(address _to, uint _value) returns (bool success){
if(balances[msg.sender] >= _value
&& _value > 0
&& balances[_to] + _value > balances[_to]){
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
else{
return false;
}
}
function transferFrom(address _from, address _to, uint _value) returns (bool success){
if(balances[_from] >= _value
&& allowed[_from][msg.sender] >= _value
&& _value >= 0
&& balances[_to] + _value > balances[_to]){
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
balances[_to] += _value;
Transfer(_from, _to, _value);
return true;
}
else{
return false;
}
}
function approve(address _spender, uint _value) returns (bool success){
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint remaining){
return allowed[_owner][_spender];
}
function DDAContract(address _dedeAddress){
dedeAddress = _dedeAddress;
balances[_dedeAddress] = _totalSupply;
Transfer(0, _dedeAddress, _totalSupply);
}
function changeDedeAddress(address newDedeAddress){
require(msg.sender == dedeAddress);
dedeAddress = newDedeAddress;
}
function mint(uint256 value){
require(msg.sender == dedeAddress);
_totalSupply += value;
balances[msg.sender] += value;
Transfer(0, msg.sender, value);
}
} | smallest unit is 10**-18, and total dda is 10**8
| uint256 public _totalSupply = 10**26; | 5,350,410 | [
1,
12019,
395,
2836,
353,
1728,
17,
2643,
16,
471,
2078,
302,
2414,
353,
23515,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
202,
11890,
5034,
1071,
389,
4963,
3088,
1283,
273,
1728,
636,
5558,
31,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2022-02-17
*/
// File: contracts/safetoken-imports.sol
/**
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.8.4;
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);
}
interface IERC20Metadata is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {return msg.sender;}
function _msgData() internal view virtual returns (bytes calldata) {this; return msg.data;}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {return a + b;}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {return a - b;}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {return a * b;}
function div(uint256 a, uint256 b) internal pure returns (uint256) {return a / b;}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {return a % b;}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked { require(b <= a, errorMessage); return a - b; }
}
}
library Address {
function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0;}
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");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {return functionCall(target, data, "Address: low-level call failed");}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {return functionCallWithValue(target, data, 0, errorMessage);}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {return functionCallWithValue(target, data, value, "Address: low-level call with value failed");}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
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);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
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);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) { return returndata; } else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {revert(errorMessage);}
}
}
}
abstract contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function getUnlockTime() public view returns (uint256) {
return _lockTime;
}
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = block.timestamp + time;
emit OwnershipTransferred(_owner, address(0));
}
function unlock() public virtual {
require(_previousOwner == msg.sender, "Only the previous owner can unlock onwership");
require(block.timestamp > _lockTime , "The contract is still locked");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
}
abstract contract Manageable is Context {
address private _manager;
event ManagementTransferred(address indexed previousManager, address indexed newManager);
constructor(){
address msgSender = _msgSender();
_manager = msgSender;
emit ManagementTransferred(address(0), msgSender);
}
function manager() public view returns(address){ return _manager; }
modifier onlyManager(){
require(_manager == _msgSender(), "Manageable: caller is not the manager");
_;
}
function transferManagement(address newManager) external virtual onlyManager {
emit ManagementTransferred(_manager, newManager);
_manager = newManager;
}
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
}
interface IUniswapV2Router {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
abstract contract Tokenomics {
using SafeMath for uint256;
// --------------------- Token Settings ------------------- //
string internal constant NAME = "Fed Inu";
string internal constant SYMBOL = "COKEN";
uint16 internal constant FEES_DIVISOR = 10 ** 3;
uint8 internal constant DECIMALS = 18;
uint256 internal constant ZEROES = 10 ** DECIMALS;
uint256 private constant MAX = ~uint256(0);
uint256 internal constant TOTAL_SUPPLY = 10 ** 12 * ZEROES;
uint256 internal _reflectedSupply = (MAX - (MAX % TOTAL_SUPPLY));
/**
* @dev Set the maximum transaction amount allowed in a transfer.
*
* The default value is 1% of the total supply.
*
* NOTE: set the value to `TOTAL_SUPPLY` to have an unlimited max, i.e.
* `maxTransactionAmount = TOTAL_SUPPLY;`
*/
uint256 internal constant maxTransactionAmount = TOTAL_SUPPLY / 100; // 1% of the total supply
/**
* @dev Set the maximum allowed balance in a wallet.
*
* The default value is 2% of the total supply.
*
* NOTE: set the value to 0 to have an unlimited max.
*
* IMPORTANT: This value MUST be greater than `numberOfTokensToSwapToLiquidity` set below,
* otherwise the liquidity swap will never be executed
*/
uint256 internal constant maxWalletBalance = TOTAL_SUPPLY;
/**
* @dev Set the number of tokens to swap and add to liquidity.
*
* Whenever the contract's balance reaches this number of tokens, swap & liquify will be
* executed in the very next transfer (via the `_beforeTokenTransfer`)
*
* If the `FeeType.Liquidity` is enabled in `FeesSettings`, the given % of each transaction will be first
* sent to the contract address. Once the contract's balance reaches `numberOfTokensToSwapToLiquidity` the
* `swapAndLiquify` of `Liquifier` will be executed. Half of the tokens will be swapped for ETH
* (or BNB on BSC) and together with the other half converted into a Token-ETH/Token-BNB LP Token.
*
* See: `Liquifier`
*/
uint256 internal constant numberOfTokensToSwapToLiquidity = TOTAL_SUPPLY / 1000; // 0.1% of the total supply
// --------------------- Fees Settings ------------------- //
/**
* @dev To add/edit/remove fees scroll down to the `addFees` function below
*/
address internal marketingAddress = 0x568E1e52E78b1799D92ed663EdE1f8Dd4b474cA7;
address internal teamAddress = 0xA6c50dafd662aB848E6B8a75BCc2571187948d83;
address internal burnAddress = 0x0000000000000000000000000000000299792458;
enum FeeType { Antiwhale, Burn, Liquidity, Rfi, External, ExternalToETH }
struct Fee {
FeeType name;
uint256 value;
address recipient;
uint256 total;
}
Fee[] internal fees;
uint256 internal sumOfFees;
constructor() {
_addFees();
}
function _addFee(FeeType name, uint256 value, address recipient) private {
fees.push( Fee(name, value, recipient, 0 ) );
sumOfFees += value;
}
function _addFees() private {
/**
* The RFI recipient is ignored but we need to give a valid address value
*
* CAUTION: If you don't want to use RFI this implementation isn't really for you!
* There are much more efficient and cleaner token contracts without RFI
* so you should use one of those
*
* The value of fees is given in part per 1000 (based on the value of FEES_DIVISOR),
* e.g. for 5% use 50, for 3.5% use 35, etc.
*/
_addFee(FeeType.Rfi, 40, address(this) );
_addFee(FeeType.Liquidity, 60, address(this) );
_addFee(FeeType.ExternalToETH, 20, teamAddress );
_addFee(FeeType.ExternalToETH, 20, marketingAddress );
}
function _getFeesCount() internal view returns (uint256){ return fees.length; }
function _getFeeStruct(uint256 index) private view returns(Fee storage){
require( index >= 0 && index < fees.length, "FeesSettings._getFeeStruct: Fee index out of bounds");
return fees[index];
}
function _getFee(uint256 index) internal view returns (FeeType, uint256, address, uint256){
Fee memory fee = _getFeeStruct(index);
return ( fee.name, fee.value, fee.recipient, fee.total );
}
function _addFeeCollectedAmount(uint256 index, uint256 amount) internal {
Fee storage fee = _getFeeStruct(index);
fee.total = fee.total.add(amount);
}
// function getCollectedFeeTotal(uint256 index) external view returns (uint256){
function getCollectedFeeTotal(uint256 index) internal view returns (uint256){
Fee memory fee = _getFeeStruct(index);
return fee.total;
}
}
abstract contract Presaleable is Manageable {
bool internal isInPresale;
function setPreseableEnabled(bool value) external onlyManager {
isInPresale = value;
}
}
abstract contract CokenRFI is IERC20, IERC20Metadata, Ownable, Presaleable, Tokenomics {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) internal _reflectedBalances;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) internal _allowances;
mapping (address => bool) internal _isExcludedFromFee;
mapping (address => bool) internal _isExcludedFromRewards;
address[] private _excluded;
constructor(){
_reflectedBalances[owner()] = _reflectedSupply;
// exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
// exclude the owner and this contract from rewards
_exclude(owner());
_exclude(address(this));
emit Transfer(address(0), owner(), TOTAL_SUPPLY);
}
/** Functions required by IERC20Metadat **/
function name() external pure override returns (string memory) { return NAME; }
function symbol() external pure override returns (string memory) { return SYMBOL; }
function decimals() external pure override returns (uint8) { return DECIMALS; }
/** Functions required by IERC20Metadat - END **/
/** Functions required by IERC20 **/
function totalSupply() external pure override returns (uint256) {
return TOTAL_SUPPLY;
}
function balanceOf(address account) public view override returns (uint256){
if (_isExcludedFromRewards[account]) return _balances[account];
return tokenFromReflection(_reflectedBalances[account]);
}
function transfer(address recipient, uint256 amount) external override returns (bool){
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) external view override returns (uint256){
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) external override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool){
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/** Functions required by IERC20 - END **/
function burn(uint256 amount) external {
address sender = _msgSender();
require(sender != address(0), "CokenRFI: burn from the zero address");
require(sender != address(burnAddress), "CokenRFI: burn from the burn address");
uint256 balance = balanceOf(sender);
require(balance >= amount, "CokenRFI: burn amount exceeds balance");
uint256 reflectedAmount = amount.mul(_getCurrentRate());
// remove the amount from the sender's balance first
_reflectedBalances[sender] = _reflectedBalances[sender].sub(reflectedAmount);
if (_isExcludedFromRewards[sender])
_balances[sender] = _balances[sender].sub(amount);
_burnTokens( sender, amount, reflectedAmount );
}
/**
* @dev "Soft" burns the specified amount of tokens by sending them
* to the burn address
*/
function _burnTokens(address sender, uint256 tBurn, uint256 rBurn) internal {
/**
* @dev Do not reduce _totalSupply and/or _reflectedSupply. (soft) burning by sending
* tokens to the burn address (which should be excluded from rewards) is sufficient
* in RFI
*/
_reflectedBalances[burnAddress] = _reflectedBalances[burnAddress].add(rBurn);
if (_isExcludedFromRewards[burnAddress])
_balances[burnAddress] = _balances[burnAddress].add(tBurn);
/**
* @dev Emit the event so that the burn address balance is updated (on bscscan)
*/
emit Transfer(sender, burnAddress, tBurn);
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
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;
}
function isExcludedFromReward(address account) external view returns (bool) {
return _isExcludedFromRewards[account];
}
/**
* @dev Calculates and returns the reflected amount for the given amount with or without
* the transfer fees (deductTransferFee true/false)
*/
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns(uint256) {
require(tAmount <= TOTAL_SUPPLY, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,) = _getValues(tAmount,0);
return rAmount;
} else {
(,uint256 rTransferAmount,,,) = _getValues(tAmount,_getSumOfFees());
return rTransferAmount;
}
}
/**
* @dev Calculates and returns the amount of tokens corresponding to the given reflected amount.
*/
function tokenFromReflection(uint256 rAmount) internal view returns(uint256) {
require(rAmount <= _reflectedSupply, "Amount must be less than total reflections");
uint256 currentRate = _getCurrentRate();
return rAmount.div(currentRate);
}
function _exclude(address account) internal {
if(_reflectedBalances[account] > 0) {
_balances[account] = tokenFromReflection(_reflectedBalances[account]);
}
_isExcludedFromRewards[account] = true;
_excluded.push(account);
}
function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; }
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "CokenRFI: approve from the zero address");
require(spender != address(0), "CokenRFI: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
*/
function _isUnlimitedSender(address account) internal view returns(bool){
// the owner should be the only whitelisted sender
return (account == owner());
}
/**
*/
function _isUnlimitedRecipient(address account) internal view returns(bool){
// the owner should be a white-listed recipient
// and anyone should be able to burn as many tokens as
// he/she wants
return (account == owner() || account == burnAddress);
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "CokenRFI: transfer from the zero address");
require(recipient != address(0), "CokenRFI: transfer to the zero address");
require(sender != address(burnAddress), "CokenRFI: transfer from the burn address");
require(amount > 0, "Transfer amount must be greater than zero");
// indicates whether or not feee should be deducted from the transfer
bool takeFee = true;
if ( isInPresale ){ takeFee = false; }
else {
/**
* Check the amount is within the max allowed limit as long as a
* unlimited sender/recepient is not involved in the transaction
*/
if ( amount > maxTransactionAmount && !_isUnlimitedSender(sender) && !_isUnlimitedRecipient(recipient) ){
revert("Transfer amount exceeds the maxTxAmount.");
}
/**
* The pair needs to excluded from the max wallet balance check;
* selling tokens is sending them back to the pair (without this
* check, selling tokens would not work if the pair's balance
* was over the allowed max)
*
* Note: This does NOT take into account the fees which will be deducted
* from the amount. As such it could be a bit confusing
*/
if ( maxWalletBalance > 0 && !_isUnlimitedSender(sender) && !_isUnlimitedRecipient(recipient) && !_isV2Pair(recipient) ){
uint256 recipientBalance = balanceOf(recipient);
require(recipientBalance + amount <= maxWalletBalance, "New balance would exceed the maxWalletBalance");
}
}
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; }
_beforeTokenTransfer(sender, recipient, amount, takeFee);
_transferTokens(sender, recipient, amount, takeFee);
}
function _transferTokens(address sender, address recipient, uint256 amount, bool takeFee) private {
/**
* We don't need to know anything about the individual fees here
* (like Safemoon does with `_getValues`). All that is required
* for the transfer is the sum of all fees to calculate the % of the total
* transaction amount which should be transferred to the recipient.
*
* The `_takeFees` call will/should take care of the individual fees
*/
uint256 sumOfFees = _getSumOfFees();
if ( !takeFee ){ sumOfFees = 0; }
(uint256 rAmount, uint256 rTransferAmount, uint256 tAmount, uint256 tTransferAmount, uint256 currentRate ) = _getValues(amount, sumOfFees);
/**
* Sender's and Recipient's reflected balances must be always updated regardless of
* whether they are excluded from rewards or not.
*/
_reflectedBalances[sender] = _reflectedBalances[sender].sub(rAmount);
_reflectedBalances[recipient] = _reflectedBalances[recipient].add(rTransferAmount);
/**
* Update the true/nominal balances for excluded accounts
*/
if (_isExcludedFromRewards[sender]){ _balances[sender] = _balances[sender].sub(tAmount); }
if (_isExcludedFromRewards[recipient] ){ _balances[recipient] = _balances[recipient].add(tTransferAmount); }
_takeFees( amount, currentRate, sumOfFees );
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeFees(uint256 amount, uint256 currentRate, uint256 sumOfFees ) private {
if ( sumOfFees > 0 && !isInPresale ){
_takeTransactionFees(amount, currentRate);
}
}
function _getValues(uint256 tAmount, uint256 feesSum) internal view returns (uint256, uint256, uint256, uint256, uint256) {
uint256 tTotalFees = tAmount.mul(feesSum).div(FEES_DIVISOR);
uint256 tTransferAmount = tAmount.sub(tTotalFees);
uint256 currentRate = _getCurrentRate();
uint256 rAmount = tAmount.mul(currentRate);
uint256 rTotalFees = tTotalFees.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rTotalFees);
return (rAmount, rTransferAmount, tAmount, tTransferAmount, currentRate);
}
function _getCurrentRate() internal view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() internal view returns(uint256, uint256) {
uint256 rSupply = _reflectedSupply;
uint256 tSupply = TOTAL_SUPPLY;
/**
* The code below removes balances of addresses excluded from rewards from
* rSupply and tSupply, which effectively increases the % of transaction fees
* delivered to non-excluded holders
*/
for (uint256 i = 0; i < _excluded.length; i++) {
if (_reflectedBalances[_excluded[i]] > rSupply || _balances[_excluded[i]] > tSupply) return (_reflectedSupply, TOTAL_SUPPLY);
rSupply = rSupply.sub(_reflectedBalances[_excluded[i]]);
tSupply = tSupply.sub(_balances[_excluded[i]]);
}
if (tSupply == 0 || rSupply < _reflectedSupply.div(TOTAL_SUPPLY)) return (_reflectedSupply, TOTAL_SUPPLY);
return (rSupply, tSupply);
}
/**
* @dev Hook that is called before any transfer of tokens.
*/
function _beforeTokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) internal virtual;
/**
* @dev Returns the total sum of fees to be processed in each transaction.
*
* To separate concerns this contract (class) will take care of ONLY handling RFI, i.e.
* changing the rates and updating the holder's balance (via `_redistribute`).
* It is the responsibility of the dev/user to handle all other fees and taxes
* in the appropriate contracts (classes).
*/
function _getSumOfFees() internal view virtual returns (uint256);
/**
* @dev A delegate which should return true if the given address is the V2 Pair and false otherwise
*/
function _isV2Pair(address account) internal view virtual returns(bool);
function _redistribute(uint256 amount, uint256 currentRate, uint256 fee, uint256 index) internal {
uint256 tFee = amount.mul(fee).div(FEES_DIVISOR);
uint256 rFee = tFee.mul(currentRate);
_reflectedSupply = _reflectedSupply.sub(rFee);
_addFeeCollectedAmount(index, tFee);
}
/**
* @dev Hook that is called before the `Transfer` event is emitted if fees are enabled for the transfer
*/
function _takeTransactionFees(uint256 amount, uint256 currentRate) internal virtual;
}
abstract contract Liquifier is Ownable, Manageable {
using SafeMath for uint256;
uint256 private withdrawableBalance;
IUniswapV2Router internal _router = IUniswapV2Router(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public _pair;
bool private inSwapAndLiquify;
bool private swapAndLiquifyEnabled = true;
uint256 private maxTransactionAmount;
uint256 private numberOfTokensToSwapToLiquidity;
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
event RouterSet(address indexed router);
event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event LiquidityAdded(uint256 tokenAmountSent, uint256 ethAmountSent, uint256 liquidity);
receive() external payable {}
function initializeLiquiditySwapper(uint256 maxTx, uint256 liquifyAmount) internal {
_pair = IUniswapV2Factory(_router.factory()).createPair(address(this), _router.WETH());
maxTransactionAmount = maxTx;
numberOfTokensToSwapToLiquidity = liquifyAmount;
}
/**
* NOTE: passing the `contractTokenBalance` here is preferred to creating `balanceOfDelegate`
*/
function liquify(uint256 contractTokenBalance, address sender) internal {
if (contractTokenBalance >= maxTransactionAmount) contractTokenBalance = maxTransactionAmount;
bool isOverRequiredTokenBalance = ( contractTokenBalance >= numberOfTokensToSwapToLiquidity );
/**
* - first check if the contract has collected enough tokens to swap and liquify
* - then check swap and liquify is enabled
* - then make sure not to get caught in a circular liquidity event
* - finally, don't swap & liquify if the sender is the uniswap pair
*/
if ( isOverRequiredTokenBalance && swapAndLiquifyEnabled && !inSwapAndLiquify && (sender != _pair) ){
// TODO check if the `(sender != _pair)` is necessary because that basically
// stops swap and liquify for all "buy" transactions
_swapAndLiquify(contractTokenBalance);
}
}
function _swapAndLiquify(uint256 amount) private lockTheSwap {
// split the contract balance into halves
uint256 half = amount.div(2);
uint256 otherHalf = amount.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
_swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity to uniswap
_addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
function _swapTokensForEth(uint256 tokenAmount) internal {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = _router.WETH();
_approveDelegate(address(this), address(_router), tokenAmount);
// make the swap
_router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function _addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approveDelegate(address(this), address(_router), tokenAmount);
// add tahe liquidity
(uint256 tokenAmountSent, uint256 ethAmountSent, uint256 liquidity) = _router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0,
0,
owner(),
block.timestamp
);
// fix the forever locked BNBs as per the certik's audit
/**
* The swapAndLiquify function converts half of the contractTokenBalance SafeMoon tokens to BNB.
* For every swapAndLiquify function call, a small amount of BNB remains in the contract.
* This amount grows over time with the swapAndLiquify function being called throughout the life
* of the contract. The Safemoon contract does not contain a method to withdraw these funds,
* and the BNB will be locked in the Safemoon contract forever.
*/
withdrawableBalance = address(this).balance;
emit LiquidityAdded(tokenAmountSent, ethAmountSent, liquidity);
}
function setSwapAndLiquifyEnabled(bool enabled) external onlyManager {
swapAndLiquifyEnabled = enabled;
emit SwapAndLiquifyEnabledUpdated(swapAndLiquifyEnabled);
}
function withdrawLockedEth(address payable recipient) external onlyManager(){
require(recipient != address(0), "Cannot withdraw the ETH balance to the zero address");
require(withdrawableBalance > 0, "The ETH balance must be greater than 0");
// prevent re-entrancy attacks
uint256 amount = withdrawableBalance;
withdrawableBalance = 0;
recipient.transfer(amount);
}
/**
* @dev Use this delegate instead of having (unnecessarily) extend `CokenRFI` to gained access
* to the `_approve` function.
*/
function _approveDelegate(address owner, address spender, uint256 amount) internal virtual;
}
contract COKEN is CokenRFI, Liquifier {
using SafeMath for uint256;
// constructor(string memory _name, string memory _symbol, uint8 _decimals){
constructor(){
_approve(owner(),address(_router), ~uint256(0));
initializeLiquiditySwapper(maxTransactionAmount, numberOfTokensToSwapToLiquidity);
// exclude the pair address from rewards - we don't want to redistribute
// tx fees to these two; redistribution is only for holders, dah!
_exclude(_pair);
_exclude(burnAddress);
}
function _isV2Pair(address account) internal view override returns(bool){
return (account == _pair);
}
function _getSumOfFees() internal view override returns (uint256){
return sumOfFees;
}
// function _beforeTokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) internal override {
function _beforeTokenTransfer(address sender, address , uint256 , bool ) internal override {
if ( !isInPresale ){
uint256 contractTokenBalance = balanceOf(address(this));
liquify( contractTokenBalance, sender );
}
}
function _takeTransactionFees(uint256 amount, uint256 currentRate) internal override {
if( isInPresale ){ return; }
uint256 feesCount = _getFeesCount();
for (uint256 index = 0; index < feesCount; index++ ){
(FeeType name, uint256 value, address recipient,) = _getFee(index);
// no need to check value < 0 as the value is uint (i.e. from 0 to 2^256-1)
if ( value == 0 ) continue;
if ( name == FeeType.Rfi ){
_redistribute( amount, currentRate, value, index );
}
else if ( name == FeeType.ExternalToETH){
_takeFeeToETH( amount, value, recipient);
}
else {
_takeFee( amount, currentRate, value, recipient, index );
}
}
}
function _burn(uint256 amount, uint256 currentRate, uint256 fee, uint256 index) private {
uint256 tBurn = amount.mul(fee).div(FEES_DIVISOR);
uint256 rBurn = tBurn.mul(currentRate);
_burnTokens(address(this), tBurn, rBurn);
_addFeeCollectedAmount(index, tBurn);
}
function _takeFee(uint256 amount, uint256 currentRate, uint256 fee, address recipient, uint256 index) private {
uint256 tAmount = amount.mul(fee).div(FEES_DIVISOR);
uint256 rAmount = tAmount.mul(currentRate);
_reflectedBalances[recipient] = _reflectedBalances[recipient].add(rAmount);
if(_isExcludedFromRewards[recipient])
_balances[recipient] = _balances[recipient].add(tAmount);
_addFeeCollectedAmount(index, tAmount);
}
/**
* @dev When implemented this will convert the fee amount of tokens into ETH/BNB
* and send to the recipient's wallet. Note that this reduces liquidity so it
* might be a good idea to add a % into the liquidity fee for % you take our through
* this method (just a suggestions)
*/
function _takeFeeToETH(uint256 amount, uint256 fee, address recipient) private {
uint256 initialBalance = address(this).balance;
uint256 _fee = amount.mul(fee).div(FEES_DIVISOR);
_swapTokensForEth(_fee);
uint256 newBalance = address(this).balance.sub(initialBalance);
payable(recipient).transfer(newBalance);
}
function _approveDelegate(address owner, address spender, uint256 amount) internal override {
_approve(owner, spender, amount);
}
} | indicates whether or not feee should be deducted from the transfer* Check the amount is within the max allowed limit as long as a unlimited sender/recepient is not involved in the transaction/* The pair needs to excluded from the max wallet balance check; selling tokens is sending them back to the pair (without this check, selling tokens would not work if the pair's balance was over the allowed max) Note: This does NOT take into account the fees which will be deducted from the amount. As such it could be a bit confusing/ | function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "CokenRFI: transfer from the zero address");
require(recipient != address(0), "CokenRFI: transfer to the zero address");
require(sender != address(burnAddress), "CokenRFI: transfer from the burn address");
require(amount > 0, "Transfer amount must be greater than zero");
bool takeFee = true;
else {
if ( amount > maxTransactionAmount && !_isUnlimitedSender(sender) && !_isUnlimitedRecipient(recipient) ){
revert("Transfer amount exceeds the maxTxAmount.");
}
if ( maxWalletBalance > 0 && !_isUnlimitedSender(sender) && !_isUnlimitedRecipient(recipient) && !_isV2Pair(recipient) ){
uint256 recipientBalance = balanceOf(recipient);
require(recipientBalance + amount <= maxWalletBalance, "New balance would exceed the maxWalletBalance");
}
}
_beforeTokenTransfer(sender, recipient, amount, takeFee);
_transferTokens(sender, recipient, amount, takeFee);
}
| 10,016,219 | [
1,
728,
8242,
2856,
578,
486,
14036,
73,
1410,
506,
11140,
853,
329,
628,
326,
7412,
2073,
326,
3844,
353,
3470,
326,
943,
2935,
1800,
487,
1525,
487,
279,
640,
21325,
5793,
19,
8606,
84,
1979,
353,
486,
24589,
316,
326,
2492,
19,
1021,
3082,
4260,
358,
8845,
628,
326,
943,
9230,
11013,
866,
31,
357,
2456,
2430,
353,
5431,
2182,
1473,
358,
326,
3082,
261,
13299,
333,
866,
16,
357,
2456,
2430,
4102,
486,
1440,
309,
326,
3082,
1807,
11013,
1703,
1879,
326,
2935,
943,
13,
3609,
30,
1220,
1552,
4269,
4862,
1368,
2236,
326,
1656,
281,
1492,
903,
506,
11140,
853,
329,
4202,
628,
326,
3844,
18,
2970,
4123,
518,
3377,
506,
279,
2831,
2195,
9940,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
13866,
12,
2867,
5793,
16,
1758,
8027,
16,
2254,
5034,
3844,
13,
3238,
288,
203,
3639,
2583,
12,
15330,
480,
1758,
12,
20,
3631,
315,
39,
969,
54,
1653,
30,
7412,
628,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
20367,
480,
1758,
12,
20,
3631,
315,
39,
969,
54,
1653,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
15330,
480,
1758,
12,
70,
321,
1887,
3631,
315,
39,
969,
54,
1653,
30,
7412,
628,
326,
18305,
1758,
8863,
203,
3639,
2583,
12,
8949,
405,
374,
16,
315,
5912,
3844,
1297,
506,
6802,
2353,
3634,
8863,
203,
540,
203,
3639,
1426,
4862,
14667,
273,
638,
31,
203,
203,
3639,
469,
288,
203,
5411,
309,
261,
3844,
405,
943,
3342,
6275,
597,
401,
67,
291,
984,
21325,
12021,
12,
15330,
13,
597,
401,
67,
291,
984,
21325,
18241,
12,
20367,
13,
262,
95,
203,
7734,
15226,
2932,
5912,
3844,
14399,
326,
943,
4188,
6275,
1199,
1769,
203,
5411,
289,
203,
5411,
309,
261,
943,
16936,
13937,
405,
374,
597,
401,
67,
291,
984,
21325,
12021,
12,
15330,
13,
597,
401,
67,
291,
984,
21325,
18241,
12,
20367,
13,
597,
401,
67,
291,
58,
22,
4154,
12,
20367,
13,
262,
95,
203,
7734,
2254,
5034,
8027,
13937,
273,
11013,
951,
12,
20367,
1769,
203,
7734,
2583,
12,
20367,
13937,
397,
3844,
1648,
943,
16936,
13937,
16,
315,
1908,
11013,
4102,
9943,
326,
943,
16936,
13937,
8863,
203,
5411,
289,
203,
3639,
289,
203,
203,
203,
3639,
389,
5771,
1345,
5912,
2
]
|
/// https://etherscan.io/address/0x06012c8cf97bead5deae237070f9587f8e7a266d#code
/// Submitted for verification at Etherscan.io on 2017-11-28
pragma solidity ^0.4.11;
/// 所有者合约拥有一个所有者,提供基本的授权控制函数,简化的用户权限的实现
contract Ownable {
address public owner; // 所有者地址
/// 构造函数设置所有者
function Ownable() {
owner = msg.sender;
}
/// 修改器前置验证所有权
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/// 转移所有权函数,要求当前所有者调用
/// 传入新的所有者地址 非 0 地址
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/// ERC721 NFT 代币接口 Non-Fungible Tokens
contract ERC721 {
// Required methods
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(
address _from,
address _to,
uint256 _tokenId
) external;
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
/// ERC165 提供函数检查是否实现了某函数
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID)
external
view
returns (bool);
}
// // Auction wrapper functions
// Auction wrapper functions
/// what? 基因科学接口
contract GeneScienceInterface {
/// 是否实现了基因科学?
function isGeneScience() public pure returns (bool);
/// 混合基因 母猫基因 公猫基因 目标块? -> 下一代基因
function mixGenes(
uint256 genes1,
uint256 genes2,
uint256 targetBlock
) public returns (uint256);
}
/// 管理特殊访问权限的门面
contract KittyAccessControl {
// 4 个角色
// CEO 角色 任命其他角色 改变依赖的合约的地址 唯一可以停止加密猫的角色 在合约初始化时设置
// CFO 角色 可以从机密猫和它的拍卖合约中提出资金
// COO 角色 可以释放第 0 代加密猫 创建推广猫咪
// 这些权限被详细的分开。虽然 CEO 可以给指派任何角色,但 CEO 并不能够直接做这些角色的工作。
// 并非有意限制,而是尽量少使用 CEO 地址。使用的越少,账户被破坏的可能性就越小。
/// 合约升级事件
event ContractUpgrade(address newContract);
// 每种角色的地址,也有可能是合约的地址.
address public ceoAddress;
address public cfoAddress;
address public cooAddress;
// 保持关注变量 paused 是否为真,一旦为真,大部分操作是不能够实行的
bool public paused = false;
/// 修改器仅限 CEO
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// 修改器仅限 CFO
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/// 修改器仅限 COO
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
/// 修改器仅限管理层(CEO 或 CFO 或 COO)
modifier onlyCLevel() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress ||
msg.sender == cfoAddress
);
_;
}
/// 设置新的 CEO 地址 仅限 CEO 操作
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// 设置新的 CFO 地址 仅限 CEO 操作
function setCFO(address _newCFO) external onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
/// 设置新的 COO 地址 仅限 CEO 操作
function setCOO(address _newCOO) external onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
// OpenZeppelin 提供了很多合约方便使用,每个都应该研究一下
/*** Pausable functionality adapted from OpenZeppelin ***/
/// 修改器仅限没有停止合约
modifier whenNotPaused() {
require(!paused);
_;
}
/// 修改器仅限已经停止合约
modifier whenPaused() {
require(paused);
_;
}
/// 停止函数 仅限管理层 未停止时 调用
/// 在遇到 bug 或者 检测到非法牟利 这时需要限制损失
/// 仅可外部调用
function pause() external onlyCLevel whenNotPaused {
paused = true;
}
/// 开始合约 仅限 CEO 已经停止时 调用
/// 不能给 CFO 或 COO 权限,因为万一他们账户被盗。
/// 注意这个方法不是外部的,公开表明可以被子合约调用
function unpause() public onlyCEO whenPaused {
// can't unpause if contract was upgraded
// what? 如果合约升级了,不能被停止??
paused = false;
}
}
/// 加密猫的基合约 包含所有普通结构体 事件 和 基本变量
contract KittyBase is KittyAccessControl {
/*** EVENTS ***/
/// 出生事件
/// giveBirth 方法触发
/// 第 0 代猫咪被创建也会被触发
event Birth(
address owner,
uint256 kittyId,
uint256 matronId,
uint256 sireId,
uint256 genes
);
/// 转账事件是 ERC721 定义的标准时间,这里猫咪第一次被赋予所有者也会触发
event Transfer(address from, address to, uint256 tokenId);
/*** DATA TYPES ***/
/// 猫咪的主要结构体,加密猫里的每个猫都要用这个结构体表示。务必确保这个结构体使用 2 个 256 位的字数。
/// 由于以太坊自己包装跪着,这个结构体中顺序很重要(改动就不满足 2 个 256 要求了)
struct Kitty {
// 猫咪的基因是 256 位,格式是 sooper-sekret 不知道这是什么格式??
uint256 genes;
// 出生的时间戳
uint64 birthTime;
// 这只猫可以再次进行繁育活动的最小时间戳 公猫和母猫都用这个时间戳 冷却时间?!
uint64 cooldownEndBlock;
// 下面 ID 用于记录猫咪的父母,对于第 0 代猫咪,设置为 0
// 采用 32 位数字,最大仅有 4 亿多点,目前够用了 截止目前 2021-09-26 有 200 万个猫咪了
uint32 matronId;
uint32 sireId;
// 母猫怀孕的话,设置为公猫的 id,否则是 0。非 0 表明猫咪怀孕了。
// 当新的猫出生时需要基因物质。
uint32 siringWithId;
// 当前猫咪的冷却时间,是冷却时间数组的序号。第 0 代猫咪开始为 0,其他的猫咪是代数除以 2,每次成功繁育后都要自增 1
uint16 cooldownIndex;
// 代数 直接由合约创建出来的是第 0 代,其他出生的猫咪由父母最大代数加 1
uint16 generation;
}
/*** 常量 ***/
/// 冷却时间查询表
/// 设计目的是鼓励玩家不要老拿一只猫进行繁育
/// 最大冷却时间是一周
uint32[14] public cooldowns = [
uint32(1 minutes),
uint32(2 minutes),
uint32(5 minutes),
uint32(10 minutes),
uint32(30 minutes),
uint32(1 hours),
uint32(2 hours),
uint32(4 hours),
uint32(8 hours),
uint32(16 hours),
uint32(1 days),
uint32(2 days),
uint32(4 days),
uint32(7 days)
];
// 目前每个块之间的时间间隔估计
uint256 public secondsPerBlock = 15;
/*** 存储 ***/
/// 所有猫咪数据的列表 ID 就是猫咪在这个列表的序号
/// id 为 0 的猫咪是神秘生物,生育了第 0 代猫咪
Kitty[] kitties;
/// 猫咪 ID 对应所有者的映射,第 0 代猫咪也有
mapping(uint256 => address) public kittyIndexToOwner;
//// 所有者对拥有猫咪数量的映射 是 ERC721 接口 balanceOf 的底层数据支持
mapping(address => uint256) ownershipTokenCount;
/// 猫咪对应的授权地址,授权地址可以取得猫咪的所有权 对应 ERC721 接口 transferFrom 方法
mapping(uint256 => address) public kittyIndexToApproved;
/// 猫咪对应授权对方可以进行繁育的数据结构 对方可以通过 breedWith 方法进行猫咪繁育
mapping(uint256 => address) public sireAllowedToAddress;
/// 定时拍卖合约的地址 点对点销售的合约 也是第 0 代猫咪每 15 分钟初始化的地方
SaleClockAuction public saleAuction;
/// 繁育拍卖合约地址 需要和销售拍卖分开 二者有很大区别,分开为好
SiringClockAuction public siringAuction;
/// 内部给予猫咪所有者的方法 仅本合约可用 what?感觉这个方法子类应该也可以调用啊???
function _transfer(
address _from,
address _to,
uint256 _tokenId
) internal {
// Since the number of kittens is capped to 2^32 we can't overflow this
// 对应地址所拥有的数量加 1
ownershipTokenCount[_to]++;
// 设置所有权
kittyIndexToOwner[_tokenId] = _to;
// 第 0 代猫咪最开始没有 from,后面才会有
if (_from != address(0)) {
// 如果有所有者
// 所有者猫咪数量减 1
ownershipTokenCount[_from]--;
// 该猫咪设置过的允许繁育的地址删除 不能被上一个所有者设置的别人可以繁育继续有效
delete sireAllowedToAddress[_tokenId];
// 该猫咪设置过的允许授权的地址删除 不能被上一个所有者设置的别人可以拿走继续有效
delete kittyIndexToApproved[_tokenId];
}
// 触发所有权变更事件,第 0 代猫咪创建之后,也会触发事件
Transfer(_from, _to, _tokenId);
}
/// 创建猫咪并存储的内部方法 不做权限参数检查,必须保证传入参数是正确的 会触发出生和转移事件
/// @param _matronId 母猫 id 第 0 代的话是 0
/// @param _sireId 公猫 id 第 0 代的话是 0
/// @param _generation 代数,必须先计算好
/// @param _genes 基因
/// @param _owner 初始所有者 (except for the unKitty, ID 0)
function _createKitty(
uint256 _matronId,
uint256 _sireId,
uint256 _generation,
uint256 _genes,
address _owner
) internal returns (uint256) {
// 这些检查是非严格检查,调用这应当确保参数是有效的,本方法依据是个非常昂贵的调用,不要再耗费 gas 检查参数了
require(_matronId == uint256(uint32(_matronId)));
require(_sireId == uint256(uint32(_sireId)));
require(_generation == uint256(uint16(_generation)));
// 新猫咪的冷却序号是代数除以 2
uint16 cooldownIndex = uint16(_generation / 2);
if (cooldownIndex > 13) {
cooldownIndex = 13;
}
Kitty memory _kitty = Kitty({
genes: _genes,
birthTime: uint64(now),
cooldownEndBlock: 0,
matronId: uint32(_matronId),
sireId: uint32(_sireId),
siringWithId: 0,
cooldownIndex: cooldownIndex,
generation: uint16(_generation)
});
uint256 newKittenId = kitties.push(_kitty) - 1;
// 确保是 32 位id
require(newKittenId == uint256(uint32(newKittenId)));
// 触发出生事件
Birth(
_owner,
newKittenId,
uint256(_kitty.matronId),
uint256(_kitty.sireId),
_kitty.genes
);
// 触发所有权转移事件
_transfer(0, _owner, newKittenId);
return newKittenId;
}
/// 设置估计的每个块间隔,这里检查必须小于 1 分钟了
/// 必须管理层调用 外部函数
function setSecondsPerBlock(uint256 secs) external onlyCLevel {
require(secs < cooldowns[0]);
secondsPerBlock = secs;
}
}
/// 外部合约 返回猫咪的元数据 只有一个方法返回字节数组数据
contract ERC721Metadata {
/// 给 id 返回字节数组数据,能转化为字符串
/// what? 这都是写死的数据,不知道有什么用
function getMetadata(uint256 _tokenId, string)
public
view
returns (bytes32[4] buffer, uint256 count)
{
if (_tokenId == 1) {
buffer[0] = "Hello World! :D";
count = 15;
} else if (_tokenId == 2) {
buffer[0] = "I would definitely choose a medi";
buffer[1] = "um length string.";
count = 49;
} else if (_tokenId == 3) {
buffer[0] = "Lorem ipsum dolor sit amet, mi e";
buffer[1] = "st accumsan dapibus augue lorem,";
buffer[2] = " tristique vestibulum id, libero";
buffer[3] = " suscipit varius sapien aliquam.";
count = 128;
}
}
}
/// 加密猫核心合约的门面 管理权限
contract KittyOwnership is KittyBase, ERC721 {
/// ERC721 接口
string public constant name = "CryptoKitties";
string public constant symbol = "CK";
// 元数据合约
ERC721Metadata public erc721Metadata;
/// 方法签名常量,ERC165 要求的方法
bytes4 constant InterfaceSignature_ERC165 =
bytes4(keccak256("supportsInterface(bytes4)"));
/// ERC721 要求的方法签名
/// 字节数组的 ^ 运算时什么意思??
/// 我明白了,ERC721 是一堆方法,不用一各一个验证,这么多方法一起合成一个值,这个值有就行了
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256("name()")) ^
bytes4(keccak256("symbol()")) ^
bytes4(keccak256("totalSupply()")) ^
bytes4(keccak256("balanceOf(address)")) ^
bytes4(keccak256("ownerOf(uint256)")) ^
bytes4(keccak256("approve(address,uint256)")) ^
bytes4(keccak256("transfer(address,uint256)")) ^
bytes4(keccak256("transferFrom(address,address,uint256)")) ^
bytes4(keccak256("tokensOfOwner(address)")) ^
bytes4(keccak256("tokenMetadata(uint256,string)"));
/// 实现 ERC165 的方法
function supportsInterface(bytes4 _interfaceID)
external
view
returns (bool)
{
// DEBUG ONLY
//require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d));
return ((_interfaceID == InterfaceSignature_ERC165) ||
(_interfaceID == InterfaceSignature_ERC721));
}
/// 设置元数据合约地址,原来这个地址是可以修改的,那么就可以更新了 仅限 CEO 修改
function setMetadataAddress(address _contractAddress) public onlyCEO {
erc721Metadata = ERC721Metadata(_contractAddress);
}
/// 内部工具函数,这些函数被假定输入参数是有效的。 参数校验留给公开方法处理。
/// 检查指定地址是否拥有某只猫咪 内部函数
function _owns(address _claimant, uint256 _tokenId)
internal
view
returns (bool)
{
return kittyIndexToOwner[_tokenId] == _claimant;
}
/// 检查某只猫咪收被授权给某地址 内部函数
function _approvedFor(address _claimant, uint256 _tokenId)
internal
view
returns (bool)
{
return kittyIndexToApproved[_tokenId] == _claimant;
}
/// 猫咪收被授权给地址 这样该地址就能够通过 transferFrom 方法取得所有权 内部函数
/// 同一时间只允许有一个授权地址,如果地址是 0 的话,表示清除授权
/// 该方法不触发事件,故意不触发事件。当前方法和transferFrom方法一起在拍卖中使用,拍卖触发授权事件没有意义。
function _approve(uint256 _tokenId, address _approved) internal {
kittyIndexToApproved[_tokenId] = _approved;
}
/// 返回某地址拥有的数量 这也是 ERC721 的方法
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
/// 转移猫咪给其他地址 修改器检查只在非停止状态下允许转移 外部函数
/// 如果是转移给其他合约的地址,请清楚行为的后果,否则有可能永久失去这只猫咪
function transfer(address _to, uint256 _tokenId) external whenNotPaused {
// 要求地址不为 0
require(_to != address(0));
/// 禁止转移给加密猫合约地址 本合约地址不应该拥有任何一只猫咪 除了再创建第 0 代并且还没进入拍卖的时候
require(_to != address(this));
/// 禁止转移给销售拍卖和繁育拍卖地址,销售拍卖对加密猫的所有权仅限于通过 授权 和 transferFrom 的方式
require(_to != address(saleAuction));
require(_to != address(siringAuction));
// 要求调用方拥有这只猫咪
require(_owns(msg.sender, _tokenId));
// 更改所有权 清空授权 触发转移事件
_transfer(msg.sender, _to, _tokenId);
}
/// 授权给其他地址 修改器检查只在非停止状态下允许 外部函数
/// 其他合约可以通过transferFrom取得所有权。这个方法被期望在授权给合约地址,参入地址为 0 的话就表明清除授权
/// ERC721 要求方法
function approve(address _to, uint256 _tokenId) external whenNotPaused {
// 要求调用方拥有这只猫咪
require(_owns(msg.sender, _tokenId));
// 进行授权
_approve(_tokenId, _to);
// 触发授权事件
Approval(msg.sender, _to, _tokenId);
}
/// 取得猫咪所有权 修改器检查只在非停止状态下允许 外部函数
/// ERC721 要求方法
function transferFrom(
address _from,
address _to,
uint256 _tokenId
) external whenNotPaused {
// 检查目标地址不是 0
require(_to != address(0));
// 禁止转移给当前合约
require(_to != address(this));
// 检查调用者是否有被授权,猫咪所有者地址是否正确
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// 更改所有权 清空授权 触发转移事件
_transfer(_from, _to, _tokenId);
}
/// 目前所有猫咪数量 公开方法 只读
/// ERC721 要求方法
function totalSupply() public view returns (uint256) {
return kitties.length - 1;
}
/// 查询某只猫咪的所有者 外部函数 只读
/// ERC721 要求方法
function ownerOf(uint256 _tokenId) external view returns (address owner) {
owner = kittyIndexToOwner[_tokenId];
require(owner != address(0));
}
/// 返回某地址拥有的所有猫咪 id 列表 外部函数 只读
/// 这个方法不应该被合约调用,因为太消耗 gas
/// 这方法返回一个动态数组,仅支持 web3 调用,不支持合约对合约的调用
function tokensOfOwner(address _owner)
external
view
returns (uint256[] ownerTokens)
{
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// 返回空数组
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalCats = totalSupply();
uint256 resultIndex = 0;
// 遍历所有的猫咪如果地址相符就记录
uint256 catId;
for (catId = 1; catId <= totalCats; catId++) {
if (kittyIndexToOwner[catId] == _owner) {
result[resultIndex] = catId;
resultIndex++;
}
}
return result;
}
}
/// 内存拷贝方法
function _memcpy(
uint256 _dest,
uint256 _src,
uint256 _len
) private view {
// Copy word-length chunks while possible
// 32 位一块一块复制
for (; _len >= 32; _len -= 32) {
assembly {
// 取出原地址 放到目标地址
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
// Copy remaining bytes
// what? 剩下的部分看不明白了 这个指数运算啥意思啊
uint256 mask = 256**(32 - _len) - 1;
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
/// 转换成字符串
function _toString(bytes32[4] _rawBytes, uint256 _stringLength)
private
view
returns (string)
{
// 先得到指定长度的字符串
var outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
// what? 这是取出指定变量的地址??
outputPtr := add(outputString, 32)
// 为啥这个就直接当地址用了??
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
return outputString;
}
/// 返回指定猫咪的元数据 包含 URI 信息
function tokenMetadata(uint256 _tokenId, string _preferredTransport)
external
view
returns (string infoUrl)
{
// 要求元数据合约地址指定
require(erc721Metadata != address(0));
bytes32[4] memory buffer;
uint256 count;
(buffer, count) = erc721Metadata.getMetadata(
_tokenId,
_preferredTransport
);
return _toString(buffer, count);
}
}
/// 加密猫核心合约的门面 管理猫咪生育 妊娠 和 出生
contract KittyBreeding is KittyOwnership {
/// 怀孕事件 当 2 只猫咪成功的饲养并怀孕
event Pregnant(
address owner,
uint256 matronId,
uint256 sireId,
uint256 cooldownEndBlock
);
/// 自动出生费? breedWithAuto方法使用,这个费用会在 giveBirth 方法中转变成 gas 消耗
/// 可以被 COO 动态更新
uint256 public autoBirthFee = 2 finney;
// 怀孕的猫咪计数
uint256 public pregnantKitties;
/// 基于科学 兄弟合约 实现基因混合算法,,
GeneScienceInterface public geneScience;
/// 设置基因合约 仅限 CEO 调用
function setGeneScienceAddress(address _address) external onlyCEO {
GeneScienceInterface candidateContract = GeneScienceInterface(_address);
require(candidateContract.isGeneScience()); // 要求是基因科学合约
geneScience = candidateContract;
}
/// 检查猫咪是否准备好繁育了 内部函数 只读 要求冷却时间结束
function _isReadyToBreed(Kitty _kit) internal view returns (bool) {
// 额外检查冷却结束的块 我们同样需要建擦猫咪是否有等待出生?? 在猫咪怀孕结束和出生事件之间存在一些时间周期??莫名其妙
// In addition to checking the cooldownEndBlock, we also need to check to see if
// the cat has a pending birth; there can be some period of time between the end
// of the pregnacy timer and the birth event.
return
(_kit.siringWithId == 0) &&
(_kit.cooldownEndBlock <= uint64(block.number));
}
/// 检查公猫是否授权和这个母猫繁育 内部函数 只读 如果是同一个所有者,或者公猫已经授权给母猫的地址,返回 true
function _isSiringPermitted(uint256 _sireId, uint256 _matronId)
internal
view
returns (bool)
{
address matronOwner = kittyIndexToOwner[_matronId];
address sireOwner = kittyIndexToOwner[_sireId];
return (matronOwner == sireOwner ||
sireAllowedToAddress[_sireId] == matronOwner);
}
/// 设置猫咪的冷却时间 基于当前冷却时间序号 同时增加冷却时间序号除非达到最大序号 内部函数
function _triggerCooldown(Kitty storage _kitten) internal {
// 计算估计冷却的块
_kitten.cooldownEndBlock = uint64(
(cooldowns[_kitten.cooldownIndex] / secondsPerBlock) + block.number
);
// 繁育序号加一 最大是 13,冷却时间数组的最大长度,本来也可以数组的长度,但是这里硬编码进常量,为了节省 gas 费
if (_kitten.cooldownIndex < 13) {
_kitten.cooldownIndex += 1;
}
}
/// 授权繁育 外部函数 仅限非停止状态
/// 地址是将要和猫咪繁育的猫咪的所有者 设置 0 地址表明取消繁育授权
function approveSiring(address _addr, uint256 _sireId)
external
whenNotPaused
{
require(_owns(msg.sender, _sireId)); // 检查猫咪所有权
sireAllowedToAddress[_sireId] = _addr; // 记录允许地址
}
/// 设置自动出生费 外部函数 仅限 COO
function setAutoBirthFee(uint256 val) external onlyCOO {
autoBirthFee = val;
}
/// 是否准备好出生 私有 只读
function _isReadyToGiveBirth(Kitty _matron) private view returns (bool) {
return
(_matron.siringWithId != 0) &&
(_matron.cooldownEndBlock <= uint64(block.number));
}
/// 检查猫咪是否准备好繁育 公开 只读
function isReadyToBreed(uint256 _kittyId) public view returns (bool) {
require(_kittyId > 0);
Kitty storage kit = kitties[_kittyId];
return _isReadyToBreed(kit);
}
/// 是否猫咪怀孕了 公开 只读
function isPregnant(uint256 _kittyId) public view returns (bool) {
require(_kittyId > 0);
// 如果 siringWithId 被设置了表明就是怀孕了
return kitties[_kittyId].siringWithId != 0;
}
/// 内部检查公猫和母猫是不是个有效对 不检查所有权
function _isValidMatingPair(
Kitty storage _matron,
uint256 _matronId,
Kitty storage _sire,
uint256 _sireId
) private view returns (bool) {
// 不能是自己
if (_matronId == _sireId) {
return false;
}
// 母猫的妈妈不能是公猫 母猫的爸爸不能是公猫
if (_matron.matronId == _sireId || _matron.sireId == _sireId) {
return false;
}
// 公猫的妈妈不能是母猫 公猫的爸爸不能是母猫
if (_sire.matronId == _matronId || _sire.sireId == _matronId) {
return false;
}
// 如果公猫或母猫的妈妈是第 0 代猫咪,允许繁育
// We can short circuit the sibling check (below) if either cat is
// gen zero (has a matron ID of zero).
if (_sire.matronId == 0 || _matron.matronId == 0) {
return true;
}
// 讲真我对加密猫的血缘检查无语了,什么乱七八糟的
// 猫咪不能与带血缘关系的繁育,同妈妈 或 公猫的妈妈和母猫的爸爸是同一个
if (
_sire.matronId == _matron.matronId ||
_sire.matronId == _matron.sireId
) {
return false;
}
// 同爸爸 或 公猫的爸爸和母猫的妈妈是同一个
if (
_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId
) {
return false;
}
// Everything seems cool! Let's get DTF.
return true;
}
/// 内部检查是否可以通过拍卖进行繁育
function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId)
internal
view
returns (bool)
{
Kitty storage matron = kitties[_matronId];
Kitty storage sire = kitties[_sireId];
return _isValidMatingPair(matron, _matronId, sire, _sireId);
}
/// 检查 2 只猫咪是否可以繁育 外部函数 只读 检查所有权授权 不检查猫咪是否准备好繁育 在冷却时间期间是不能繁育成功的
function canBreedWith(uint256 _matronId, uint256 _sireId)
external
view
returns (bool)
{
require(_matronId > 0);
require(_sireId > 0);
Kitty storage matron = kitties[_matronId];
Kitty storage sire = kitties[_sireId];
return
_isValidMatingPair(matron, _matronId, sire, _sireId) &&
_isSiringPermitted(_sireId, _matronId);
}
/// 内部工具函数初始化繁育 假定所有的繁育要求已经满足 内部函数
function _breedWith(uint256 _matronId, uint256 _sireId) internal {
// 获取猫咪信息
Kitty storage sire = kitties[_sireId];
Kitty storage matron = kitties[_matronId];
// 标记母猫怀孕 指向公猫
matron.siringWithId = uint32(_sireId);
// 设置冷却时间
_triggerCooldown(sire);
_triggerCooldown(matron);
// 情况授权繁育地址,似乎多次一句,这里可以避免困惑
// tips 如果别人指向授权给某个人。每次繁育后还要继续设置,岂不是很烦躁
delete sireAllowedToAddress[_matronId];
delete sireAllowedToAddress[_sireId];
// 怀孕的猫咪计数加 1
pregnantKitties++;
// 触发怀孕事件
Pregnant(
kittyIndexToOwner[_matronId],
_matronId,
_sireId,
matron.cooldownEndBlock
);
}
/// 自动哺育一个猫咪 外部函数 可支付 仅限非停止状态
/// 哺育一个猫咪 作为母猫提供者,和公猫提供者 或 被授权的公猫
/// 猫咪是否会怀孕 或 完全失败 要看 giveBirth 函数给与的预支付的费用
function breedWithAuto(uint256 _matronId, uint256 _sireId)
external
payable
whenNotPaused
{
require(msg.value >= autoBirthFee); // 要求大于自动出生费
require(_owns(msg.sender, _matronId)); // 要求是母猫所有者
// 哺育操作期间 允许猫咪被拍卖 拍卖的事情这里不关心
// 对于母猫:这个方法的调用者不会是母猫的所有者,因为猫咪的所有者是拍卖合约 拍卖合约不会调用繁育方法
// 对于公猫:统一,公猫也属于拍卖合约,转移猫咪会清除繁育授权
// 因此我们不花费 gas 费检查猫咪是否属于拍卖合约
// 检查猫咪是否都属于调用者 或 公猫是给与授权的
require(_isSiringPermitted(_sireId, _matronId));
Kitty storage matron = kitties[_matronId]; // 获取母猫信息
require(_isReadyToBreed(matron)); // 确保母猫不是怀孕状态 或者 哺育冷却期
Kitty storage sire = kitties[_sireId]; // 获取公猫信息
require(_isReadyToBreed(sire)); // 确保公猫不是怀孕状态 或者 哺育冷却期
require(_isValidMatingPair(matron, _matronId, sire, _sireId)); // 确保猫咪是有效的匹配
_breedWith(_matronId, _sireId); // 进行繁育任务
}
/// 已经有怀孕的猫咪 才能 出生 外部函数 仅限非暂停状态
/// 如果怀孕并且妊娠时间已经过了 联合基因创建一个新的猫咪
/// 新的猫咪所有者是母猫的所有者
/// 知道成功的结束繁育,公猫和母猫才会进入下个准备阶段
/// 注意任何人可以调用这个方法 只要他们愿意支付 gas 费用 但是新猫咪仍然属于母猫的所有者
function giveBirth(uint256 _matronId)
external
whenNotPaused
returns (uint256)
{
Kitty storage matron = kitties[_matronId]; // 获取母猫信息
require(matron.birthTime != 0); // 要求母猫是有效的猫咪
// Check that the matron is pregnant, and that its time has come!
require(_isReadyToGiveBirth(matron)); // 要求母猫准备好生猫咪 是怀孕状态并且时间已经到了
uint256 sireId = matron.siringWithId; // 公猫 id
Kitty storage sire = kitties[sireId]; // 公猫信息
uint16 parentGen = matron.generation; // 母猫代数
if (sire.generation > matron.generation) {
parentGen = sire.generation; // 如果公猫代数高,则用公猫代数
}
// 调用混合基因的方法
uint256 childGenes = geneScience.mixGenes(
matron.genes,
sire.genes,
matron.cooldownEndBlock - 1
);
// 制作新猫咪
address owner = kittyIndexToOwner[_matronId];
uint256 kittenId = _createKitty(
_matronId,
matron.siringWithId,
parentGen + 1,
childGenes,
owner
);
delete matron.siringWithId; // 清空母猫的配对公猫 id
pregnantKitties--; // 每次猫咪出生,计数器减 1
msg.sender.send(autoBirthFee); // 支付给调用方自动出生费用
return kittenId; // 返回猫咪 id
}
}
/// 定时拍卖核心 包含 结构 变量 内置方法
contract ClockAuctionBase {
// 一个 NFT 拍卖的表示
struct Auction {
// NFT 当前所有者
address seller;
// 开始拍卖的价格 单位 wei
uint128 startingPrice;
// 结束买卖的价格 单位 wei
uint128 endingPrice;
// 拍卖持续时间 单位秒
uint64 duration;
// 拍卖开始时间 如果是 0 表示拍卖已经结束
uint64 startedAt;
}
// 关联的 NFT 合约
ERC721 public nonFungibleContract;
// 每次拍卖收税 0-10000 对应这 0%-100%
uint256 public ownerCut;
// 每只猫对应的拍卖信息
mapping(uint256 => Auction) tokenIdToAuction;
/// 拍卖创建事件
event AuctionCreated(
uint256 tokenId,
uint256 startingPrice,
uint256 endingPrice,
uint256 duration
);
/// 拍卖成功事件
event AuctionSuccessful(
uint256 tokenId,
uint256 totalPrice,
address winner
);
/// 拍卖取消事件
event AuctionCancelled(uint256 tokenId);
/// 某地址是否拥有某只猫咪 内部函数 只读
function _owns(address _claimant, uint256 _tokenId)
internal
view
returns (bool)
{
return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
}
/// 托管猫咪 将猫咪托管给当前拍卖合约
function _escrow(address _owner, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transferFrom(_owner, this, _tokenId);
}
/// NFT 转账 内部函数
function _transfer(address _receiver, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transfer(_receiver, _tokenId);
}
/// 增加拍卖 触发拍卖事件 内部函数
function _addAuction(uint256 _tokenId, Auction _auction) internal {
// Require that all auctions have a duration of
// at least one minute. (Keeps our math from getting hairy!)
require(_auction.duration >= 1 minutes);
tokenIdToAuction[_tokenId] = _auction;
// 触发拍卖创建事件
AuctionCreated(
uint256(_tokenId),
uint256(_auction.startingPrice),
uint256(_auction.endingPrice),
uint256(_auction.duration)
);
}
/// 取消拍卖 触发取消事件 内部函数
function _cancelAuction(uint256 _tokenId, address _seller) internal {
_removeAuction(_tokenId);
_transfer(_seller, _tokenId);
AuctionCancelled(_tokenId);
}
/// 计算价格并转移 NFT 给胜者 内部函数
function _bid(uint256 _tokenId, uint256 _bidAmount)
internal
returns (uint256)
{
// 获取拍卖数据
Auction storage auction = tokenIdToAuction[_tokenId];
// 要求拍卖属于激活状态
require(_isOnAuction(auction));
// 要求出价不低于当前价格
uint256 price = _currentPrice(auction);
require(_bidAmount >= price);
// 获取卖家地址
address seller = auction.seller;
// 移除这个猫咪的拍卖
_removeAuction(_tokenId);
// 转账给卖家
if (price > 0) {
// 计算拍卖费用
uint256 auctioneerCut = _computeCut(price);
uint256 sellerProceeds = price - auctioneerCut;
// 进行转账
// 在一个复杂的方法中惊调用转账方法是不被鼓励的,因为可能遇到可重入个攻击或者拒绝服务攻击.
// 我们明确的通过移除拍卖来防止充入攻击,卖价用 DOS 操作只能攻击他自己的资产
// 如果真有意外发生,可以通过调用取消拍卖
seller.transfer(sellerProceeds);
}
// 计算超出的额度
uint256 bidExcess = _bidAmount - price;
// 返还超出的费用
msg.sender.transfer(bidExcess);
// 触发拍卖成功事件
AuctionSuccessful(_tokenId, price, msg.sender);
return price;
}
/// 删除拍卖 内部函数
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
/// 判断拍卖是否为激活状态 内部函数 只读
function _isOnAuction(Auction storage _auction)
internal
view
returns (bool)
{
return (_auction.startedAt > 0);
}
/// 计算当前价格 内部函数 只读
/// 需要 2 个函数
/// 当前函数 计算事件 另一个 计算价格
function _currentPrice(Auction storage _auction)
internal
view
returns (uint256)
{
uint256 secondsPassed = 0;
// 确保正值
if (now > _auction.startedAt) {
secondsPassed = now - _auction.startedAt;
}
return
_computeCurrentPrice(
_auction.startingPrice,
_auction.endingPrice,
_auction.duration,
secondsPassed
);
}
/// 计算拍卖的当前价格 内部函数 纯计算
function _computeCurrentPrice(
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
uint256 _secondsPassed
) internal pure returns (uint256) {
// 没有是有 SafeMath 或类似的函数,是因为所有公开方法 时间最大值是 64 位 货币最大只是 128 位
if (_secondsPassed >= _duration) {
// 超出时间就是最后的价格
return _endingPrice;
} else {
// 线性插值?? 讲真我觉得不算拍卖,明明是插值价格
int256 totalPriceChange = int256(_endingPrice) -
int256(_startingPrice);
int256 currentPriceChange = (totalPriceChange *
int256(_secondsPassed)) / int256(_duration);
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
return uint256(currentPrice);
}
}
/// 收取拍卖费用 内部函数 只读
function _computeCut(uint256 _price) internal view returns (uint256) {
return (_price * ownerCut) / 10000;
}
}
/// 可停止的合约
contract Pausable is Ownable {
event Pause(); // 停止事件
event Unpause(); // 继续事件
bool public paused = false; // what? 不是已经有一个 paused 了吗?? 上面的是管理层控制的中止 这个是所有者控制的中止 合约很多
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
function unpause() onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
/// 定时拍卖
contract ClockAuction is Pausable, ClockAuctionBase {
/// ERC721 接口的方法常量 ERC165 接口返回
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d);
/// 构造器函数 传入 nft 合约地址和手续费率
function ClockAuction(address _nftAddress, uint256 _cut) public {
require(_cut <= 10000);
ownerCut = _cut;
ERC721 candidateContract = ERC721(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
nonFungibleContract = candidateContract;
}
/// 提出余额 外部方法
function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
// 要求是所有者或 nft 合约
require(msg.sender == owner || msg.sender == nftAddress);
// 使用 send 确保就算转账失败也能继续运行
bool res = nftAddress.send(this.balance);
}
/// 创建一个新的拍卖 外部方法 仅限非停止状态
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
) external whenNotPaused {
require(_startingPrice == uint256(uint128(_startingPrice))); // 检查开始价格
require(_endingPrice == uint256(uint128(_endingPrice))); // 检查结束价格
require(_duration == uint256(uint64(_duration))); // 检查拍卖持续时间
require(_owns(msg.sender, _tokenId)); // 检查所有者权限
_escrow(msg.sender, _tokenId); // 托管猫咪给合约
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction); // 保存拍卖信息
}
/// 购买一个拍卖 完成拍卖和转移所有权 外部函数 可支付 仅限非停止状态
function bid(uint256 _tokenId) external payable whenNotPaused {
_bid(_tokenId, msg.value); // 入股购买资金转移失败,会报异常
_transfer(msg.sender, _tokenId);
}
/// 取消没有胜者的拍卖 外部函数
/// 注意这个方法可以再合约被停止的情况下调用
function cancelAuction(uint256 _tokenId) external {
Auction storage auction = tokenIdToAuction[_tokenId]; // 找到拍卖信息
require(_isOnAuction(auction)); // 检查拍卖是否激活状态 讲真的,从某种设计的角度来说,我觉得这种检查放到拍卖合约里面检查比较好,额,当前合约就是拍卖合约。。。
address seller = auction.seller; // 卖家地址
require(msg.sender == seller); // 检查调用者是不是卖家地址
_cancelAuction(_tokenId, seller); // 取消拍卖
}
/// 取消拍卖 外部函数 仅限停止状态 仅限合约拥有者调用
/// 紧急情况下使用的方法
function cancelAuctionWhenPaused(uint256 _tokenId)
external
whenPaused
onlyOwner
{
Auction storage auction = tokenIdToAuction[_tokenId]; // 找到拍卖信息
require(_isOnAuction(auction)); // 检查是否激活状态
_cancelAuction(_tokenId, auction.seller); // 取消拍卖
}
/// 返回拍卖信息 外部函数 只读
function getAuction(uint256 _tokenId)
external
view
returns (
address seller,
uint256 startingPrice,
uint256 endingPrice,
uint256 duration,
uint256 startedAt
)
{
Auction storage auction = tokenIdToAuction[_tokenId]; // 找到拍卖信息
require(_isOnAuction(auction)); // 检查拍卖是激活状态
return (
auction.seller,
auction.startingPrice,
auction.endingPrice,
auction.duration,
auction.startedAt
);
}
/// 获取拍卖当前价格 外部函数 只读
function getCurrentPrice(uint256 _tokenId) external view returns (uint256) {
Auction storage auction = tokenIdToAuction[_tokenId]; // 找到拍卖信息
require(_isOnAuction(auction)); // 检查拍卖是激活状态
return _currentPrice(auction); // 计算当前价格
}
}
/// 繁育拍卖合约
contract SiringClockAuction is ClockAuction {
// 在setSiringAuctionAddress方法调用中,合约检查确保我们在操作正确的拍卖
bool public isSiringClockAuction = true;
// 委托父合约构造函数
function SiringClockAuction(address _nftAddr, uint256 _cut)
public
ClockAuction(_nftAddr, _cut)
{}
/// 创建一个拍卖 外部函数
/// 包装函数 要求调用方必须是 KittyCore 核心
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
) external {
require(_startingPrice == uint256(uint128(_startingPrice))); // 检查开始价格
require(_endingPrice == uint256(uint128(_endingPrice))); // 检查结束价格
require(_duration == uint256(uint64(_duration))); // 检查拍卖持续时间
require(msg.sender == address(nonFungibleContract)); // 要求调用者是 nft 合约地址
_escrow(_seller, _tokenId); // 授权拍卖
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction); // 添加拍卖信息
}
/// 发起一个出价 外部函数 可支付
/// 要求调用方是 KittyCore 合约 因为所有的出价方法都被包装
/// 同样退回猫咪给卖家 看不懂说的啥 Also returns the kitty to the seller rather than the winner.
function bid(uint256 _tokenId) external payable {
require(msg.sender == address(nonFungibleContract));
address seller = tokenIdToAuction[_tokenId].seller;
_bid(_tokenId, msg.value);
_transfer(seller, _tokenId);
}
}
/// 销售拍卖合约
contract SaleClockAuction is ClockAuction {
// 在setSaleAuctionAddress方法调用中,合约检查确保我们在操作正确的拍卖
bool public isSaleClockAuction = true;
uint256 public gen0SaleCount; // 第 0 代猫咪售出计数
uint256[5] public lastGen0SalePrices; // 记录最近 5 只第 0 代卖出价格
// 委托父合约构造函数
function SaleClockAuction(address _nftAddr, uint256 _cut)
public
ClockAuction(_nftAddr, _cut)
{}
/// 创建新的拍卖
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
) external {
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// 如果卖家是 NFT合约 更新价格
function bid(uint256 _tokenId) external payable {
// _bid verifies token ID size
address seller = tokenIdToAuction[_tokenId].seller;
uint256 price = _bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
// If not a gen0 auction, exit
if (seller == address(nonFungibleContract)) {
// Track gen0 sale prices
lastGen0SalePrices[gen0SaleCount % 5] = price;
gen0SaleCount++;
}
}
/// 平均第 0 代售价 外部函数 只读
function averageGen0SalePrice() external view returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < 5; i++) {
sum += lastGen0SalePrices[i];
}
return sum / 5;
}
}
/// 猫咪拍卖合约 创建销售和繁育的拍卖
/// This wrapper of ReverseAuction exists only so that users can create
/// auctions with only one transaction.
contract KittyAuction is KittyBreeding {
// 当前拍卖合约变量定义在 KittyBase 中,KittyOwnership中有对变量的检查
// 销售拍卖参考第 0 代拍卖和 p2p 销售
// 繁育拍卖参考猫咪的繁育权拍卖
/// 设置销售拍卖合约 外部函数 仅限 CEO 调用
function setSaleAuctionAddress(address _address) external onlyCEO {
SaleClockAuction candidateContract = SaleClockAuction(_address);
require(candidateContract.isSaleClockAuction());
saleAuction = candidateContract;
}
/// 设置繁育排满合约 外部函数 仅限 CEO 调用
function setSiringAuctionAddress(address _address) external onlyCEO {
SiringClockAuction candidateContract = SiringClockAuction(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isSiringClockAuction());
// Set the new contract address
siringAuction = candidateContract;
}
/// 将一只猫咪放入销售拍卖 外部函数 仅限非停止状态调用
function createSaleAuction(
uint256 _kittyId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
) external whenNotPaused {
// 拍卖合约检查输入参数大小
// 如果猫咪已经在拍卖中了,会报异常,因为所有权在拍卖合约那里
require(_owns(msg.sender, _kittyId));
// 确保猫咪不在怀孕状态 防止买到猫咪的人收到小猫咪的所有权
require(!isPregnant(_kittyId));
_approve(_kittyId, saleAuction); // 授权猫咪所有权给拍卖合约
// 如果参数有误拍卖合约会报异常。 调用成功会清除转移和繁育授权
saleAuction.createAuction(
_kittyId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
/// 将一只猫咪放入繁育拍卖 外部函数 仅限非停止状态调用
function createSiringAuction(
uint256 _kittyId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
) external whenNotPaused {
// 拍卖合约检查输入参数大小
// 如果猫咪已经在拍卖中了,会报异常,因为所有权在拍卖合约那里
require(_owns(msg.sender, _kittyId));
require(isReadyToBreed(_kittyId)); // 检查猫咪是否在哺育状态
_approve(_kittyId, siringAuction); // 授权猫咪所有权给拍卖合约
// 如果参数有误拍卖合约会报异常。 调用成功会清除转移和繁育授权
siringAuction.createAuction(
_kittyId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
/// 出价完成一个繁育合约 猫咪会立即进入哺育状态 外部函数 可以支付 仅当非停止状态
function bidOnSiringAuction(uint256 _sireId, uint256 _matronId)
external
payable
whenNotPaused
{
// 拍卖合约检查输入大小
require(_owns(msg.sender, _matronId));
require(isReadyToBreed(_matronId));
require(_canBreedWithViaAuction(_matronId, _sireId));
// 计算当前价格
uint256 currentPrice = siringAuction.getCurrentPrice(_sireId);
require(msg.value >= currentPrice + autoBirthFee); // 出价要高于当前价格和自动出生费用
// 如果出价失败,繁育合约会报异常
siringAuction.bid.value(msg.value - autoBirthFee)(_sireId);
_breedWith(uint32(_matronId), uint32(_sireId));
}
/// 转移拍卖合约的余额到 KittyCore 外部函数仅限管理层调用
function withdrawAuctionBalances() external onlyCLevel {
saleAuction.withdrawBalance();
siringAuction.withdrawBalance();
}
}
/// 所有关系到创建猫咪的函数
contract KittyMinting is KittyAuction {
// 限制合约创建猫咪的数量
uint256 public constant PROMO_CREATION_LIMIT = 5000;
uint256 public constant GEN0_CREATION_LIMIT = 45000;
// 第 0 代猫咪拍卖的常数
uint256 public constant GEN0_STARTING_PRICE = 10 finney;
uint256 public constant GEN0_AUCTION_DURATION = 1 days;
// 合约创建猫咪计数
uint256 public promoCreatedCount;
uint256 public gen0CreatedCount;
/// 创建推广猫咪 外部函数 仅限 COO 调用
function createPromoKitty(uint256 _genes, address _owner) external onlyCOO {
address kittyOwner = _owner;
if (kittyOwner == address(0)) {
kittyOwner = cooAddress;
}
require(promoCreatedCount < PROMO_CREATION_LIMIT);
promoCreatedCount++;
_createKitty(0, 0, 0, _genes, kittyOwner);
}
/// 创建第 0 代猫咪 外部函数 仅限 COO 调用
/// 为猫咪创建一个拍卖
function createGen0Auction(uint256 _genes) external onlyCOO {
require(gen0CreatedCount < GEN0_CREATION_LIMIT);
uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this));
_approve(kittyId, saleAuction);
saleAuction.createAuction(
kittyId,
_computeNextGen0Price(),
0,
GEN0_AUCTION_DURATION,
address(this)
);
gen0CreatedCount++;
}
/// 计算第 0 代拍卖的价格 最后 5 个价格平均值 + 50% 内部函数 只读
function _computeNextGen0Price() internal view returns (uint256) {
uint256 avePrice = saleAuction.averageGen0SalePrice();
// Sanity check to ensure we don't overflow arithmetic
require(avePrice == uint256(uint128(avePrice)));
uint256 nextPrice = avePrice + (avePrice / 2);
// We never auction for less than starting price
if (nextPrice < GEN0_STARTING_PRICE) {
nextPrice = GEN0_STARTING_PRICE;
}
return nextPrice;
}
}
/// 加密猫核心 收集 哺育 领养?
contract KittyCore is KittyMinting {
// 这是加密猫的主要合约。为了让代码和逻辑部分分开,我们采用了 2 种方式。
// 第一,我们分开了部分兄弟合约管理拍卖和我们最高秘密的基因混合算法。
// 拍卖分开因为逻辑在某些方面比较复杂,另外也总是存在小 bug 的风险。
// 让这些风险在它们自己的合约里,我们可以升级它们,同时不用干扰记录着猫咪所有权的主合约。
// 基因混合算法分离是因为我们可以开源其他部分的算法,同时防止别人很容易就分叉弄明白基因部分是如何工作的。不用担心,我确定很快就会有人对齐逆向工程。
// 第二,我们分开核心合约产生多个文件是为了使用继承。这让我们保持关联的代码紧紧绑在一起,也避免了所有的东西都在一个巨型文件里。
// 分解如下:
//
// - KittyBase: 这是我们定义大多数基础代码的地方,这些代码贯穿了核心功能。包括主要数据存储,常量和数据类型,还有管理这些的内部函数。
//
// - KittyAccessControl: 这个合约管理多种地址和限制特殊角色操作,像是 CEO CFO COO
//
// - KittyOwnership: 这个合约提供了基本的 NFT token 交易 请看 ERC721
//
// - KittyBreeding: 这个包含了必要的哺育猫咪相关的方法,包括保证对公猫提供者的记录和对外部基因混合合约的依赖
//
// - KittyAuctions: 这里我们有许多拍卖、出价和繁育的方法,实际的拍卖功能存储在 2 个兄弟合约(一个管销售 一个管繁育),拍卖创建和出价都要通过这个合约操作。
//
// - KittyMinting: 这是包含创建第 0 代猫咪的最终门面合约。我们会制作 5000 个推广猫咪,这样的猫咪可以被分出去,比如当社区建立时。
// 所有的其他猫咪仅仅能够通过创建并立即进入拍卖,价格通过算法计算的方式分发出去。不要关心猫咪是如何被创建的,有一个 5 万的硬性限制。之后的猫咪都只能通过繁育生产。
// 当核心合约被破坏并且有必要升级时,设置这个变量
address public newContractAddress;
/// 构造函数 创建主要的加密猫的合约实例
function KittyCore() public {
paused = true; // 开始是暂停状态
ceoAddress = msg.sender; // 设置 ceo 地址
cooAddress = msg.sender; // 设置 coo 地址
// 创建神秘之猫,这个猫咪会产生第 0 代猫咪
_createKitty(0, 0, 0, uint256(-1), address(0));
}
///用于标记智能合约升级 防止出现严重 bug,这个方法只是记录新合约地址并触发合约升级事件。在这种情况下,客户端要采用新的合约地址。若升级发生,本合约会处于停止状态。
function setNewAddress(address _v2Address) external onlyCEO whenPaused {
// 看 README.md 了解升级计划
newContractAddress = _v2Address;
ContractUpgrade(_v2Address); // 触发合约升级事件
}
/// fallback 函数 退回所有发送到本合约的以太币 除非是销售拍卖合约和繁育拍卖合约发来的
function() external payable {
require(
msg.sender == address(saleAuction) ||
msg.sender == address(siringAuction)
);
}
/// 获取猫咪信息
function getKitty(uint256 _id)
external
view
returns (
bool isGestating,
bool isReady,
uint256 cooldownIndex,
uint256 nextActionAt,
uint256 siringWithId,
uint256 birthTime,
uint256 matronId,
uint256 sireId,
uint256 generation,
uint256 genes
)
{
Kitty storage kit = kitties[_id];
isGestating = (kit.siringWithId != 0); // 如果 siringWithId 不是 0 表明处于妊娠状态
isReady = (kit.cooldownEndBlock <= block.number);
cooldownIndex = uint256(kit.cooldownIndex);
nextActionAt = uint256(kit.cooldownEndBlock);
siringWithId = uint256(kit.siringWithId);
birthTime = uint256(kit.birthTime);
matronId = uint256(kit.matronId);
sireId = uint256(kit.sireId);
generation = uint256(kit.generation);
genes = kit.genes;
}
/// 启动合约 要求所有的外部合约地址都被设置,才能够启动合约。如果升级合约被设置了,那么无法启动合约 公开函数 要求 CEO 才能调用 仅限合约停止状态调用
/// public 我们才能调用父合约的外部方法
function unpause() public onlyCEO whenPaused {
require(saleAuction != address(0));
require(siringAuction != address(0));
require(geneScience != address(0));
require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
// 提现方法 外部 仅限 CFO
function withdrawBalance() external onlyCFO {
uint256 balance = this.balance;
// 减去所有怀孕的猫咪数量+1作为余量
uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee;
if (balance > subtractFees) {
cfoAddress.send(balance - subtractFees);
}
}
}
| 检查 2 只猫咪是否可以繁育 外部函数 只读 检查所有权授权 不检查猫咪是否准备好繁育 在冷却时间期间是不能繁育成功的 | function canBreedWith(uint256 _matronId, uint256 _sireId)
external
view
returns (bool)
{
require(_matronId > 0);
require(_sireId > 0);
Kitty storage matron = kitties[_matronId];
Kitty storage sire = kitties[_sireId];
return
_isValidMatingPair(matron, _matronId, sire, _sireId) &&
_isSiringPermitted(_sireId, _matronId);
}
| 967,906 | [
1,
167,
101,
227,
167,
258,
103,
576,
225,
166,
242,
108,
168,
239,
109,
166,
245,
108,
167,
251,
112,
166,
243,
104,
166,
242,
112,
165,
124,
103,
168,
122,
228,
169,
229,
115,
225,
166,
102,
249,
170,
230,
106,
166,
234,
126,
167,
248,
113,
225,
166,
242,
108,
169,
112,
124,
225,
167,
101,
227,
167,
258,
103,
167,
236,
227,
167,
255,
236,
167,
256,
230,
167,
241,
235,
167,
256,
230,
225,
165,
121,
240,
167,
101,
227,
167,
258,
103,
168,
239,
109,
166,
245,
108,
167,
251,
112,
166,
243,
104,
166,
234,
233,
166,
102,
234,
166,
103,
126,
168,
122,
228,
169,
229,
115,
225,
166,
255,
106,
166,
233,
120,
166,
240,
117,
167,
250,
119,
170,
250,
117,
167,
255,
258,
170,
250,
117,
167,
251,
112,
165,
121,
240,
169,
230,
126,
168,
122,
228,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
565,
445,
848,
38,
15656,
1190,
12,
11890,
5034,
389,
7373,
1949,
548,
16,
2254,
5034,
389,
87,
577,
548,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
2583,
24899,
7373,
1949,
548,
405,
374,
1769,
203,
3639,
2583,
24899,
87,
577,
548,
405,
374,
1769,
203,
3639,
1475,
305,
4098,
2502,
4834,
1949,
273,
31758,
88,
606,
63,
67,
7373,
1949,
548,
15533,
203,
3639,
1475,
305,
4098,
2502,
272,
577,
273,
31758,
88,
606,
63,
67,
87,
577,
548,
15533,
203,
3639,
327,
203,
5411,
389,
26810,
49,
1776,
4154,
12,
7373,
1949,
16,
389,
7373,
1949,
548,
16,
272,
577,
16,
389,
87,
577,
548,
13,
597,
203,
5411,
389,
291,
55,
11256,
31465,
24899,
87,
577,
548,
16,
389,
7373,
1949,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2022-03-13
*/
// File: bveCVX.sol
pragma solidity ^0.6.11;
pragma experimental ABIEncoderV2;
// File: AddressUpgradeable.sol
/**
* @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 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: ICVXBribes.sol
interface ICVXBribes {
function getReward(address _account, address _token) external;
function getRewards(address _account, address[] calldata _tokens) external;
}
// File: IController.sol
interface IController {
function withdraw(address, uint256) external;
function strategies(address) external view returns (address);
function balanceOf(address) external view returns (uint256);
function earn(address, uint256) external;
function want(address) external view returns (address);
function rewards() external view returns (address);
function vaults(address) external view returns (address);
}
// File: ICurvePool.sol
interface ICurvePool {
function exchange(
int128 i,
int128 j,
uint256 _dx,
uint256 _min_dy
) external returns (uint256);
}
// File: ICvxLocker.sol
interface ICvxLocker {
function maximumBoostPayment() external view returns (uint256);
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external;
function getReward(address _account, bool _stake) external;
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount);
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user)
external
view
returns (uint256 amount);
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external;
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external;
}
// File: IDelegateRegistry.sol
///@dev Snapshot Delegate registry so we can delegate voting to XYZ
interface IDelegateRegistry {
function setDelegate(bytes32 id, address delegate) external;
function delegation(address, bytes32) external returns (address);
}
// File: IERC20Upgradeable.sol
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @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: ISettV4.sol
interface ISettV4 {
function deposit(uint256 _amount) external;
function depositFor(address _recipient, uint256 _amount) external;
function withdraw(uint256 _amount) external;
function balance() external view returns (uint256);
function getPricePerFullShare() external view returns (uint256);
function balanceOf(address) external view returns (uint256);
function totalSupply() external view returns (uint256);
}
// File: IStrategy.sol
interface IStrategy {
function want() external view returns (address);
function deposit() external;
// NOTE: must exclude any tokens used in the yield
// Controller role - withdraw should return to Controller
function withdrawOther(address) external returns (uint256 balance);
// Controller | Vault role - withdraw should always return to Vault
function withdraw(uint256) external;
// Controller | Vault role - withdraw should always return to Vault
function withdrawAll() external returns (uint256);
function balanceOf() external view returns (uint256);
function getName() external pure returns (string memory);
function setStrategist(address _strategist) external;
function setWithdrawalFee(uint256 _withdrawalFee) external;
function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist)
external;
function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance)
external;
function setGovernance(address _governance) external;
function setController(address _controller) external;
function tend() external;
function harvest() external;
}
// File: IUniswapRouterV2.sol
interface IUniswapRouterV2 {
function factory() external view 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 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 swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
// File: IVotiumBribes.sol
interface IVotiumBribes {
struct claimParam {
address token;
uint256 index;
uint256 amount;
bytes32[] merkleProof;
}
function claimMulti(address account, claimParam[] calldata claims) external;
function claim(address token, uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external;
}
// File: Initializable.sol
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can\'t have a constructor, it\'s common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-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 || _isConstructor() || !_initialized,
"Initializable: contract is already 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;
// solhint-disable-next-line no-inline-assembly
assembly {
cs := extcodesize(self)
}
return cs == 0;
}
}
// File: MathUpgradeable.sol
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
/**
* @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: ReentrancyGuard.sol
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot\'s contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler\'s defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction\'s gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: SafeMathUpgradeable.sol
/**
* @dev Wrappers over Solidity\'s arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it\'s recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @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: ContextUpgradeable.sol
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {}
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;
}
uint256[50] private __gap;
}
// File: ReentrancyGuardUpgradeable.sol
/**
* @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 ReentrancyGuardUpgradeable is Initializable {
// 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;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_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;
}
uint256[49] private __gap;
}
// File: SafeERC20Upgradeable.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transfer.selector, to, value)
);
}
function safeTransferFrom(
IERC20Upgradeable 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(
IERC20Upgradeable 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(
IERC20Upgradeable 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(
IERC20Upgradeable 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(IERC20Upgradeable 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: SettAccessControl.sol
/*
Common base for permissioned roles throughout Sett ecosystem
*/
contract SettAccessControl is Initializable {
address public governance;
address public strategist;
address public keeper;
// ===== MODIFIERS =====
function _onlyGovernance() internal view {
require(msg.sender == governance, "onlyGovernance");
}
function _onlyGovernanceOrStrategist() internal view {
require(
msg.sender == strategist || msg.sender == governance,
"onlyGovernanceOrStrategist"
);
}
function _onlyAuthorizedActors() internal view {
require(
msg.sender == keeper || msg.sender == governance,
"onlyAuthorizedActors"
);
}
// ===== PERMISSIONED ACTIONS =====
/// @notice Change strategist address
/// @notice Can only be changed by governance itself
function setStrategist(address _strategist) external {
_onlyGovernance();
strategist = _strategist;
}
/// @notice Change keeper address
/// @notice Can only be changed by governance itself
function setKeeper(address _keeper) external {
_onlyGovernance();
keeper = _keeper;
}
/// @notice Change governance address
/// @notice Can only be changed by governance itself
function setGovernance(address _governance) public {
_onlyGovernance();
governance = _governance;
}
uint256[50] private __gap;
}
// File: PausableUpgradeable.sol
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
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 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;
}
// File: BaseStrategy.sol
/*
===== Badger Base Strategy =====
Common base class for all Sett strategies
Changelog
V1.1
- Verify amount unrolled from strategy positions on withdraw() is within a threshold relative to the requested amount as a sanity check
- Add version number which is displayed with baseStrategyVersion(). If a strategy does not implement this function, it can be assumed to be 1.0
V1.2
- Remove idle want handling from base withdraw() function. This should be handled as the strategy sees fit in _withdrawSome()
*/
abstract contract BaseStrategy is PausableUpgradeable, SettAccessControl {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
event Withdraw(uint256 amount);
event WithdrawAll(uint256 balance);
event WithdrawOther(address token, uint256 amount);
event SetStrategist(address strategist);
event SetGovernance(address governance);
event SetController(address controller);
event SetWithdrawalFee(uint256 withdrawalFee);
event SetPerformanceFeeStrategist(uint256 performanceFeeStrategist);
event SetPerformanceFeeGovernance(uint256 performanceFeeGovernance);
event Harvest(uint256 harvested, uint256 indexed blockNumber);
event Tend(uint256 tended);
address public want; // Want: Curve.fi renBTC/wBTC (crvRenWBTC) LP token
uint256 public performanceFeeGovernance;
uint256 public performanceFeeStrategist;
uint256 public withdrawalFee;
uint256 public constant MAX_FEE = 10000;
address public constant uniswap =
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Uniswap Dex
address public controller;
address public guardian;
uint256 public withdrawalMaxDeviationThreshold;
function __BaseStrategy_init(
address _governance,
address _strategist,
address _controller,
address _keeper,
address _guardian
) public initializer whenNotPaused {
__Pausable_init();
governance = _governance;
strategist = _strategist;
keeper = _keeper;
controller = _controller;
guardian = _guardian;
withdrawalMaxDeviationThreshold = 50;
}
// ===== Modifiers =====
function _onlyController() internal view {
require(msg.sender == controller, "onlyController");
}
function _onlyAuthorizedActorsOrController() internal view {
require(
msg.sender == keeper ||
msg.sender == governance ||
msg.sender == controller,
"onlyAuthorizedActorsOrController"
);
}
function _onlyAuthorizedPausers() internal view {
require(
msg.sender == guardian || msg.sender == governance,
"onlyPausers"
);
}
/// ===== View Functions =====
function baseStrategyVersion() public view returns (string memory) {
return "1.2";
}
/// @notice Get the balance of want held idle in the Strategy
function balanceOfWant() public view returns (uint256) {
return IERC20Upgradeable(want).balanceOf(address(this));
}
/// @notice Get the total balance of want realized in the strategy, whether idle or active in Strategy positions.
function balanceOf() public view virtual returns (uint256) {
return balanceOfWant().add(balanceOfPool());
}
function isTendable() public view virtual returns (bool) {
return false;
}
/// ===== Permissioned Actions: Governance =====
function setGuardian(address _guardian) external {
_onlyGovernance();
guardian = _guardian;
}
function setWithdrawalFee(uint256 _withdrawalFee) external {
_onlyGovernance();
require(
_withdrawalFee <= MAX_FEE,
"base-strategy/excessive-withdrawal-fee"
);
withdrawalFee = _withdrawalFee;
}
function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist)
external
{
_onlyGovernance();
require(
_performanceFeeStrategist <= MAX_FEE,
"base-strategy/excessive-strategist-performance-fee"
);
performanceFeeStrategist = _performanceFeeStrategist;
}
function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance)
external
{
_onlyGovernance();
require(
_performanceFeeGovernance <= MAX_FEE,
"base-strategy/excessive-governance-performance-fee"
);
performanceFeeGovernance = _performanceFeeGovernance;
}
function setController(address _controller) external {
_onlyGovernance();
controller = _controller;
}
function setWithdrawalMaxDeviationThreshold(uint256 _threshold) external {
_onlyGovernance();
require(
_threshold <= MAX_FEE,
"base-strategy/excessive-max-deviation-threshold"
);
withdrawalMaxDeviationThreshold = _threshold;
}
function deposit() public virtual whenNotPaused {
_onlyAuthorizedActorsOrController();
uint256 _want = IERC20Upgradeable(want).balanceOf(address(this));
if (_want > 0) {
_deposit(_want);
}
_postDeposit();
}
// ===== Permissioned Actions: Controller =====
/// @notice Controller-only function to Withdraw partial funds, normally used with a vault withdrawal
function withdrawAll()
external
virtual
whenNotPaused
returns (uint256 balance)
{
_onlyController();
_withdrawAll();
_transferToVault(IERC20Upgradeable(want).balanceOf(address(this)));
}
/// @notice Withdraw partial funds from the strategy, unrolling from strategy positions as necessary
/// @notice Processes withdrawal fee if present
/// @dev If it fails to recover sufficient funds (defined by withdrawalMaxDeviationThreshold), the withdrawal should fail so that this unexpected behavior can be investigated
function withdraw(uint256 _amount) external virtual whenNotPaused {
_onlyController();
// Withdraw from strategy positions, typically taking from any idle want first.
_withdrawSome(_amount);
uint256 _postWithdraw =
IERC20Upgradeable(want).balanceOf(address(this));
// Sanity check: Ensure we were able to retrieve sufficent want from strategy positions
// If we end up with less than the amount requested, make sure it does not deviate beyond a maximum threshold
if (_postWithdraw < _amount) {
uint256 diff = _diff(_amount, _postWithdraw);
// Require that difference between expected and actual values is less than the deviation threshold percentage
require(
diff <=
_amount.mul(withdrawalMaxDeviationThreshold).div(MAX_FEE),
"base-strategy/withdraw-exceed-max-deviation-threshold"
);
}
// Return the amount actually withdrawn if less than amount requested
uint256 _toWithdraw = MathUpgradeable.min(_postWithdraw, _amount);
// Process withdrawal fee
uint256 _fee = _processWithdrawalFee(_toWithdraw);
// Transfer remaining to Vault to handle withdrawal
_transferToVault(_toWithdraw.sub(_fee));
}
// NOTE: must exclude any tokens used in the yield
// Controller role - withdraw should return to Controller
function withdrawOther(address _asset)
external
virtual
whenNotPaused
returns (uint256 balance)
{
_onlyController();
_onlyNotProtectedTokens(_asset);
balance = IERC20Upgradeable(_asset).balanceOf(address(this));
IERC20Upgradeable(_asset).safeTransfer(controller, balance);
}
/// ===== Permissioned Actions: Authoized Contract Pausers =====
function pause() external {
_onlyAuthorizedPausers();
_pause();
}
function unpause() external {
_onlyGovernance();
_unpause();
}
/// ===== Internal Helper Functions =====
/// @notice If withdrawal fee is active, take the appropriate amount from the given value and transfer to rewards recipient
/// @return The withdrawal fee that was taken
function _processWithdrawalFee(uint256 _amount) internal returns (uint256) {
if (withdrawalFee == 0) {
return 0;
}
uint256 fee = _amount.mul(withdrawalFee).div(MAX_FEE);
IERC20Upgradeable(want).safeTransfer(
IController(controller).rewards(),
fee
);
return fee;
}
/// @dev Helper function to process an arbitrary fee
/// @dev If the fee is active, transfers a given portion in basis points of the specified value to the recipient
/// @return The fee that was taken
function _processFee(
address token,
uint256 amount,
uint256 feeBps,
address recipient
) internal returns (uint256) {
if (feeBps == 0) {
return 0;
}
uint256 fee = amount.mul(feeBps).div(MAX_FEE);
IERC20Upgradeable(token).safeTransfer(recipient, fee);
return fee;
}
/// @dev Reset approval and approve exact amount
function _safeApproveHelper(
address token,
address recipient,
uint256 amount
) internal {
IERC20Upgradeable(token).safeApprove(recipient, 0);
IERC20Upgradeable(token).safeApprove(recipient, amount);
}
function _transferToVault(uint256 _amount) internal {
address _vault = IController(controller).vaults(address(want));
require(_vault != address(0), "!vault"); // additional protection so we don\'t burn the funds
IERC20Upgradeable(want).safeTransfer(_vault, _amount);
}
/// @notice Swap specified balance of given token on Uniswap with given path
function _swap(
address startToken,
uint256 balance,
address[] memory path
) internal {
_safeApproveHelper(startToken, uniswap, balance);
IUniswapRouterV2(uniswap).swapExactTokensForTokens(
balance,
0,
path,
address(this),
now
);
}
function _swapEthIn(uint256 balance, address[] memory path) internal {
IUniswapRouterV2(uniswap).swapExactETHForTokens{value: balance}(
0,
path,
address(this),
now
);
}
function _swapEthOut(
address startToken,
uint256 balance,
address[] memory path
) internal {
_safeApproveHelper(startToken, uniswap, balance);
IUniswapRouterV2(uniswap).swapExactTokensForETH(
balance,
0,
path,
address(this),
now
);
}
/// @notice Add liquidity to uniswap for specified token pair, utilizing the maximum balance possible
function _add_max_liquidity_uniswap(address token0, address token1)
internal
virtual
{
uint256 _token0Balance =
IERC20Upgradeable(token0).balanceOf(address(this));
uint256 _token1Balance =
IERC20Upgradeable(token1).balanceOf(address(this));
_safeApproveHelper(token0, uniswap, _token0Balance);
_safeApproveHelper(token1, uniswap, _token1Balance);
IUniswapRouterV2(uniswap).addLiquidity(
token0,
token1,
_token0Balance,
_token1Balance,
0,
0,
address(this),
block.timestamp
);
}
/// @notice Utility function to diff two numbers, expects higher value in first position
function _diff(uint256 a, uint256 b) internal pure returns (uint256) {
require(a >= b, "diff/expected-higher-number-in-first-position");
return a.sub(b);
}
// ===== Abstract Functions: To be implemented by specific Strategies =====
/// @dev Internal deposit logic to be implemented by Stratgies
function _deposit(uint256 _amount) internal virtual;
function _postDeposit() internal virtual {
//no-op by default
}
/// @notice Specify tokens used in yield process, should not be available to withdraw via withdrawOther()
function _onlyNotProtectedTokens(address _asset) internal virtual;
function getProtectedTokens()
external
view
virtual
returns (address[] memory);
/// @dev Internal logic for strategy migration. Should exit positions as efficiently as possible
function _withdrawAll() internal virtual;
/// @dev Internal logic for partial withdrawals. Should exit positions as efficiently as possible.
/// @dev The withdraw() function shell automatically uses idle want in the strategy before attempting to withdraw more using this
function _withdrawSome(uint256 _amount) internal virtual returns (uint256);
/// @dev Realize returns from positions
/// @dev Returns can be reinvested into positions, or distributed in another fashion
/// @dev Performance fees should also be implemented in this function
/// @dev Override function stub is removed as each strategy can have it\'s own return signature for STATICCALL
// function harvest() external virtual;
/// @dev User-friendly name for this strategy for purposes of convenient reading
function getName() external pure virtual returns (string memory);
/// @dev Balance of want currently held in strategy positions
function balanceOfPool() public view virtual returns (uint256);
uint256[49] private __gap;
}
// File: MyStrategy.sol
/**
* CHANGELOG
* V1.0 Initial Release, can lock
* V1.1 Update to handle rewards which are sent to a multisig
* V1.2 Update to emit badger, all other rewards are sent to multisig
* V1.3 Updated Address to claim CVX Rewards
* V1.4 Updated Claiming mechanism to allow claiming any token (using difference in balances)
* V1.5 Unlocks are permissioneless, added Chainlink Keepeers integration
* V1.6 New Locker, work towards fully permissioneless claiming // Protected Launch
*/
contract MyStrategy is BaseStrategy, ReentrancyGuardUpgradeable {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
uint256 public constant MAX_BPS = 10_000;
// address public want // Inherited from BaseStrategy, the token the strategy wants, swaps into and tries to grow
address public lpComponent; // Token we provide liquidity with
address public reward; // Token we farm and swap to want / lpComponent
address public constant BADGER_TREE = 0x660802Fc641b154aBA66a62137e71f331B6d787A;
IDelegateRegistry public constant SNAPSHOT =
IDelegateRegistry(0x469788fE6E9E9681C6ebF3bF78e7Fd26Fc015446);
// The initial DELEGATE for the strategy // NOTE we can change it by using manualSetDelegate below
address public constant DELEGATE =
0x14F83fF95D4Ec5E8812DDf42DA1232b0ba1015e6;
bytes32 public constant DELEGATED_SPACE =
0x6376782e65746800000000000000000000000000000000000000000000000000;
ISettV4 public constant CVXCRV_VAULT =
ISettV4(0x2B5455aac8d64C14786c3a29858E43b5945819C0);
// NOTE: Locker V2
ICvxLocker public constant LOCKER = ICvxLocker(0x72a19342e8F1838460eBFCCEf09F6585e32db86E);
ICVXBribes public constant CVX_EXTRA_REWARDS = ICVXBribes(0xDecc7d761496d30F30b92Bdf764fb8803c79360D);
IVotiumBribes public constant VOTIUM_BRIBE_CLAIMER = IVotiumBribes(0x378Ba9B73309bE80BF4C2c027aAD799766a7ED5A);
// We hardcode, an upgrade is required to change this as it\'s a meaningful change
address public constant BRIBES_RECEIVER = 0x6F76C6A1059093E21D8B1C13C4e20D8335e2909F;
// We emit badger through the tree to the vault holders
address public constant BADGER = 0x3472A5A71965499acd81997a54BBA8D852C6E53d;
bool public withdrawalSafetyCheck = false;
bool public harvestOnRebalance = false;
// If nothing is unlocked, processExpiredLocks will revert
bool public processLocksOnReinvest = false;
bool public processLocksOnRebalance = false;
// Used to signal to the Badger Tree that rewards where sent to it
event TreeDistribution(
address indexed token,
uint256 amount,
uint256 indexed blockNumber,
uint256 timestamp
);
event RewardsCollected(
address token,
uint256 amount
);
event PerformanceFeeGovernance(
address indexed destination,
address indexed token,
uint256 amount,
uint256 indexed blockNumber,
uint256 timestamp
);
event PerformanceFeeStrategist(
address indexed destination,
address indexed token,
uint256 amount,
uint256 indexed blockNumber,
uint256 timestamp
);
function initialize(
address _governance,
address _strategist,
address _controller,
address _keeper,
address _guardian,
address[3] memory _wantConfig,
uint256[3] memory _feeConfig
) public initializer {
__BaseStrategy_init(
_governance,
_strategist,
_controller,
_keeper,
_guardian
);
__ReentrancyGuard_init();
/// @dev Add config here
want = _wantConfig[0];
lpComponent = _wantConfig[1];
reward = _wantConfig[2];
performanceFeeGovernance = _feeConfig[0];
performanceFeeStrategist = _feeConfig[1];
withdrawalFee = _feeConfig[2];
IERC20Upgradeable(reward).safeApprove(address(CVXCRV_VAULT), type(uint256).max);
/// @dev do one off approvals here
// Permissions for Locker
IERC20Upgradeable(want).safeApprove(address(LOCKER), type(uint256).max);
// Delegate voting to DELEGATE
SNAPSHOT.setDelegate(DELEGATED_SPACE, DELEGATE);
}
/// ===== Extra Functions =====
/// @dev Change Delegation to another address
function manualSetDelegate(address delegate) external {
_onlyGovernance();
// Set delegate is enough as it will clear previous delegate automatically
SNAPSHOT.setDelegate(DELEGATED_SPACE, delegate);
}
///@dev Should we check if the amount requested is more than what we can return on withdrawal?
function setWithdrawalSafetyCheck(bool newWithdrawalSafetyCheck) external {
_onlyGovernance();
withdrawalSafetyCheck = newWithdrawalSafetyCheck;
}
///@dev Should we harvest before doing manual rebalancing
///@notice you most likely want to skip harvest if everything is unlocked, or there\'s something wrong and you just want out
function setHarvestOnRebalance(bool newHarvestOnRebalance) external {
_onlyGovernance();
harvestOnRebalance = newHarvestOnRebalance;
}
///@dev Should we processExpiredLocks during reinvest?
function setProcessLocksOnReinvest(bool newProcessLocksOnReinvest) external {
_onlyGovernance();
processLocksOnReinvest = newProcessLocksOnReinvest;
}
///@dev Should we processExpiredLocks during manualRebalance?
function setProcessLocksOnRebalance(bool newProcessLocksOnRebalance)
external
{
_onlyGovernance();
processLocksOnRebalance = newProcessLocksOnRebalance;
}
// Claiming functions, wrote on 10th of March with goal of removing access controls on 10th June
/// @dev Function to move rewards that are not protected
/// @notice Only not protected, moves the whole amount using _handleRewardTransfer
/// @notice because token paths are harcoded, this function is safe to be called by anyone
function sweepRewardToken(address token) public nonReentrant {
_onlyGovernanceOrStrategist();
_onlyNotProtectedTokens(token);
uint256 toSend = IERC20Upgradeable(token).balanceOf(address(this));
_handleRewardTransfer(token, toSend);
}
/// @dev Bulk function for sweepRewardToken
function sweepRewards(address[] calldata tokens) external {
uint256 length = tokens.length;
for(uint i = 0; i < length; i++){
sweepRewardToken(tokens[i]);
}
}
/// @dev Skim away want to bring back ppfs to 1e18
/// @notice permissioneless function as all paths are hardcoded // In the future
function skim() external nonReentrant {
_onlyGovernanceOrStrategist();
// Just withdraw and deposit into more of the vault, and send it to tree
uint256 beforeBalance = _getBalance();
uint256 totalSupply = _getTotalSupply();
// Take the excess amount that is throwing off peg
// Works because both are in 1e18
uint256 excessAmount = beforeBalance.sub(totalSupply);
if(excessAmount == 0) { return; }
_sentTokenToBribesReceiver(want, excessAmount);
// Check that ppfs is 1, back to peg
// getPricePerFullShare == balance().mul(1e18).div(totalSupply())
require(_getBalance() == _getTotalSupply()); // Proof we skimmed only back to 1 ppfs
}
/// @dev given a token address, and convexAddress claim that as reward from CVX Extra Rewards
/// @notice funds are transfered to the hardcoded address BRIBES_RECEIVER
function claimBribeFromConvex (ICVXBribes convexAddress, address token) external nonReentrant {
_onlyGovernanceOrStrategist();
uint256 beforeVaultBalance = _getBalance();
uint256 beforePricePerFullShare = _getPricePerFullShare();
uint256 beforeBalance = IERC20Upgradeable(token).balanceOf(address(this));
// Claim reward for token
convexAddress.getReward(address(this), token);
uint256 afterBalance = IERC20Upgradeable(token).balanceOf(address(this));
_handleRewardTransfer(token, afterBalance.sub(beforeBalance));
require(beforeVaultBalance == _getBalance(), "Balance can\'t change");
require(beforePricePerFullShare == _getPricePerFullShare(), "Ppfs can\'t change");
}
/// @dev Given the ExtraRewards address and a list of tokens, claims and processes them
/// @notice permissioneless function as all paths are hardcoded // In the future
/// @notice allows claiming any token as it uses the difference in balance
function claimBribesFromConvex(ICVXBribes convexAddress, address[] memory tokens) external nonReentrant {
_onlyGovernanceOrStrategist();
uint256 beforeVaultBalance = _getBalance();
uint256 beforePricePerFullShare = _getPricePerFullShare();
// Also checks balance diff
uint256 length = tokens.length;
uint256[] memory beforeBalance = new uint256[](length);
for(uint i = 0; i < length; i++){
beforeBalance[i] = IERC20Upgradeable(tokens[i]).balanceOf(address(this));
}
// Claim reward for tokens
convexAddress.getRewards(address(this), tokens);
// Send reward to Multisig
for(uint x = 0; x < length; x++){
_handleRewardTransfer(tokens[x], IERC20Upgradeable(tokens[x]).balanceOf(address(this)).sub(beforeBalance[x]));
}
require(beforeVaultBalance == _getBalance(), "Balance can\'t change");
require(beforePricePerFullShare == _getPricePerFullShare(), "Ppfs can\'t change");
}
/// @dev given the votium data and their tree address (available at: https://github.com/oo-00/Votium/tree/main/merkle)
/// @dev allows claiming of rewards, badger is sent to tree
function claimBribeFromVotium(
IVotiumBribes votiumTree,
address token,
uint256 index,
address account,
uint256 amount,
bytes32[] calldata merkleProof
) external nonReentrant {
_onlyGovernanceOrStrategist();
uint256 beforeVaultBalance = _getBalance();
uint256 beforePricePerFullShare = _getPricePerFullShare();
uint256 beforeBalance = IERC20Upgradeable(token).balanceOf(address(this));
votiumTree.claim(token, index, account, amount, merkleProof);
uint256 afterBalance = IERC20Upgradeable(token).balanceOf(address(this));
_handleRewardTransfer(token, afterBalance.sub(beforeBalance));
require(beforeVaultBalance == _getBalance(), "Balance can\'t change");
require(beforePricePerFullShare == _getPricePerFullShare(), "Ppfs can\'t change");
}
/// @dev given the votium data (available at: https://github.com/oo-00/Votium/tree/main/merkle)
/// @dev allows claiming of multiple rewards rewards, badger is sent to tree
/// @notice permissioneless function as all paths are hardcoded // In the future
/// @notice allows claiming any token as it uses the difference in balance
function claimBribesFromVotium(
IVotiumBribes votiumTree,
address account,
address[] calldata tokens,
uint256[] calldata indexes,
uint256[] calldata amounts,
bytes32[][] calldata merkleProofs
) external nonReentrant {
_onlyGovernanceOrStrategist();
uint256 beforeVaultBalance = _getBalance();
uint256 beforePricePerFullShare = _getPricePerFullShare();
require(tokens.length == indexes.length && tokens.length == amounts.length && tokens.length == merkleProofs.length, "Length Mismatch");
// tokens.length = length, can\'t declare var as stack too deep
uint256[] memory beforeBalance = new uint256[](tokens.length);
for(uint i = 0; i < tokens.length; i++){
beforeBalance[i] = IERC20Upgradeable(tokens[i]).balanceOf(address(this));
}
IVotiumBribes.claimParam[] memory request = new IVotiumBribes.claimParam[](tokens.length);
for(uint x = 0; x < tokens.length; x++){
request[x] = IVotiumBribes.claimParam({
token: tokens[x],
index: indexes[x],
amount: amounts[x],
merkleProof: merkleProofs[x]
});
}
votiumTree.claimMulti(account, request);
for(uint i = 0; i < tokens.length; i++){
address token = tokens[i]; // Caching it allows it to compile else we hit stack too deep
_handleRewardTransfer(token, IERC20Upgradeable(token).balanceOf(address(this)).sub(beforeBalance[i]));
}
require(beforeVaultBalance == _getBalance(), "Balance can\'t change");
require(beforePricePerFullShare == _getPricePerFullShare(), "Ppfs can\'t change");
}
// END TRUSTLESS
/// *** Handling of rewards ***
function _handleRewardTransfer(address token, uint256 amount) internal {
// NOTE: BADGER is emitted through the tree
if (token == BADGER){
_sendBadgerToTree(amount);
} else {
// NOTE: All other tokens are sent to multisig
_sentTokenToBribesReceiver(token, amount);
}
}
/// @dev Send funds to the bribes receiver
function _sentTokenToBribesReceiver(address token, uint256 amount) internal {
IERC20Upgradeable(token).safeTransfer(BRIBES_RECEIVER, amount);
emit RewardsCollected(token, amount);
}
/// @dev Send the BADGER token to the badgerTree
function _sendBadgerToTree(uint256 amount) internal {
IERC20Upgradeable(BADGER).safeTransfer(BADGER_TREE, amount);
emit TreeDistribution(BADGER, amount, block.number, block.timestamp);
}
/// @dev Get the current Vault.balance
/// @notice this is reflexive, a change in the strat will change the balance in the vault
function _getBalance() internal returns (uint256) {
ISettV4 vault = ISettV4(IController(controller).vaults(want));
return vault.balance();
}
/// @dev Get the current Vault.totalSupply
function _getTotalSupply() internal returns (uint256) {
ISettV4 vault = ISettV4(IController(controller).vaults(want));
return vault.totalSupply();
}
function _getPricePerFullShare() internal returns (uint256) {
ISettV4 vault = ISettV4(IController(controller).vaults(want));
return vault.getPricePerFullShare();
}
/// ===== View Functions =====
function getBoostPayment() public view returns(uint256){
// uint256 maximumBoostPayment = LOCKER.maximumBoostPayment();
// require(maximumBoostPayment <= 1500, "over max payment"); //max 15%
return 0; // Unused at this stage, so for security reasons we just zero it
}
/// @dev Specify the name of the strategy
function getName() external pure override returns (string memory) {
return "veCVX Voting Strategy";
}
/// @dev Specify the version of the Strategy, for upgrades
function version() external pure returns (string memory) {
return "1.6";
}
/// @dev Balance of want currently held in strategy positions
function balanceOfPool() public view override returns (uint256) {
// Return the balance in locker
return LOCKER.lockedBalanceOf(address(this));
}
/// @dev Returns true if this strategy requires tending
function isTendable() public view override returns (bool) {
return false;
}
// @dev These are the tokens that cannot be moved except by the vault
function getProtectedTokens()
public
view
override
returns (address[] memory)
{
address[] memory protectedTokens = new address[](3);
protectedTokens[0] = want;
protectedTokens[1] = lpComponent; // vlCVX
protectedTokens[2] = reward; // cvxCRV //
return protectedTokens;
}
/// ===== Internal Core Implementations =====
/// @dev security check to avoid moving tokens that would cause a rugpull, edit based on strat
function _onlyNotProtectedTokens(address _asset) internal override {
address[] memory protectedTokens = getProtectedTokens();
for (uint256 x = 0; x < protectedTokens.length; x++) {
require(
address(protectedTokens[x]) != _asset,
"Asset is protected"
);
}
}
/// @dev invest the amount of want
/// @notice When this function is called, the controller has already sent want to this
/// @notice Just get the current balance and then invest accordingly
function _deposit(uint256 _amount) internal override {
// Lock tokens for 16 weeks, send credit to strat, always use max boost cause why not?
LOCKER.lock(address(this), _amount, getBoostPayment());
}
/// @dev utility function to withdraw all CVX that we can from the lock
function prepareWithdrawAll() external {
manualProcessExpiredLocks();
}
/// @dev utility function to withdraw everything for migration
/// @dev NOTE: You cannot call this unless you have rebalanced to have only CVX left in the vault
function _withdrawAll() internal override {
//NOTE: This probably will always fail unless we have all tokens expired
require(
LOCKER.lockedBalanceOf(address(this)) == 0 &&
LOCKER.balanceOf(address(this)) == 0,
"You have to wait for unlock or have to manually rebalance out of it"
);
// Make sure to call prepareWithdrawAll before _withdrawAll
}
/// @dev withdraw the specified amount of want, liquidate from lpComponent to want, paying off any necessary debt for the conversion
function _withdrawSome(uint256 _amount)
internal
override
returns (uint256)
{
uint256 max = balanceOfWant();
if(_amount > max){
// Try to unlock, as much as possible
// @notice Reverts if no locks expired
LOCKER.processExpiredLocks(false);
max = balanceOfWant();
}
if (withdrawalSafetyCheck) {
require(
max >= _amount.mul(9_980).div(MAX_BPS),
"Withdrawal Safety Check"
); // 20 BP of slippage
}
if (_amount > max) {
return max;
}
return _amount;
}
/// @dev Harvest from strategy mechanics, realizing increase in underlying position
function harvest() public whenNotPaused returns (uint256) {
_onlyAuthorizedActors();
uint256 _beforeReward = IERC20Upgradeable(reward).balanceOf(address(this));
// Get cvxCRV
LOCKER.getReward(address(this), false);
// Rewards Math
uint256 earnedReward =
IERC20Upgradeable(reward).balanceOf(address(this)).sub(_beforeReward);
uint256 cvxCrvToGovernance = earnedReward.mul(performanceFeeGovernance).div(MAX_FEE);
if(cvxCrvToGovernance > 0){
CVXCRV_VAULT.depositFor(IController(controller).rewards(), cvxCrvToGovernance);
emit PerformanceFeeGovernance(IController(controller).rewards(), address(CVXCRV_VAULT), cvxCrvToGovernance, block.number, block.timestamp);
}
uint256 cvxCrvToStrategist = earnedReward.mul(performanceFeeStrategist).div(MAX_FEE);
if(cvxCrvToStrategist > 0){
CVXCRV_VAULT.depositFor(strategist, cvxCrvToStrategist);
emit PerformanceFeeStrategist(strategist, address(CVXCRV_VAULT), cvxCrvToStrategist, block.number, block.timestamp);
}
// Send rest of earned to tree //We send all rest to avoid dust and avoid protecting the token
// We take difference of vault token to emit the event in shares rather than underlying
uint256 cvxCRVInitialBalance = CVXCRV_VAULT.balanceOf(BADGER_TREE);
uint256 cvxCrvToTree = IERC20Upgradeable(reward).balanceOf(address(this));
CVXCRV_VAULT.depositFor(BADGER_TREE, cvxCrvToTree);
uint256 cvxCRVAfterBalance = CVXCRV_VAULT.balanceOf(BADGER_TREE);
emit TreeDistribution(address(CVXCRV_VAULT), cvxCRVAfterBalance.sub(cvxCRVInitialBalance), block.number, block.timestamp);
/// @dev Harvest event that every strategy MUST have, see BaseStrategy
emit Harvest(earnedReward, block.number);
/// @dev Harvest must return the amount of want increased
return earnedReward;
}
/// @dev Rebalance, Compound or Pay off debt here
function tend() external whenNotPaused {
revert("no op"); // NOTE: For now tend is replaced by manualRebalance
}
/// MANUAL FUNCTIONS ///
/// @dev manual function to reinvest all CVX that was locked
function reinvest() external whenNotPaused returns (uint256) {
_onlyGovernance();
if (processLocksOnReinvest) {
// Withdraw all we can
LOCKER.processExpiredLocks(false);
}
// Redeposit all into veCVX
uint256 toDeposit = IERC20Upgradeable(want).balanceOf(address(this));
// Redeposit into veCVX
_deposit(toDeposit);
return toDeposit;
}
/// @dev process all locks, to redeem
/// @notice No Access Control Checks, anyone can unlock an expired lock
function manualProcessExpiredLocks() public whenNotPaused {
// Unlock veCVX that is expired and redeem CVX back to this strat
LOCKER.processExpiredLocks(false);
}
function checkUpkeep(bytes calldata checkData) external view returns (bool upkeepNeeded, bytes memory performData) {
// We need to unlock funds if the lockedBalance (locked + unlocked) is greater than the balance (actively locked for this epoch)
upkeepNeeded = LOCKER.lockedBalanceOf(address(this)) > LOCKER.balanceOf(address(this));
}
/// @dev Function for ChainLink Keepers to automatically process expired locks
function performUpkeep(bytes calldata performData) external {
// Works like this because it reverts if lock is not expired
LOCKER.processExpiredLocks(false);
}
/// @dev Send all available CVX to the Vault
/// @notice you can do this so you can earn again (re-lock), or just to add to the redemption pool
function manualSendCVXToVault() external whenNotPaused {
_onlyGovernance();
uint256 cvxAmount = IERC20Upgradeable(want).balanceOf(address(this));
_transferToVault(cvxAmount);
}
/// @dev use the currently available CVX to lock
/// @notice toLock = 0, lock nothing, deposit in CVX as much as you can
/// @notice toLock = 10_000, lock everything (CVX) you have
function manualRebalance(uint256 toLock) external whenNotPaused {
_onlyGovernance();
require(toLock <= MAX_BPS, "Max is 100%");
if (processLocksOnRebalance) {
// manualRebalance will revert if you have no expired locks
LOCKER.processExpiredLocks(false);
}
if (harvestOnRebalance) {
harvest();
}
// Token that is highly liquid
uint256 balanceOfWant =
IERC20Upgradeable(want).balanceOf(address(this));
// Locked CVX in the locker
uint256 balanceInLock = LOCKER.balanceOf(address(this));
uint256 totalCVXBalance =
balanceOfWant.add(balanceInLock);
// Amount we want to have in lock
uint256 newLockAmount = totalCVXBalance.mul(toLock).div(MAX_BPS);
// We can\'t unlock enough, no-op
if (newLockAmount <= balanceInLock) {
return;
}
// If we\'re continuing, then we are going to lock something
uint256 cvxToLock = newLockAmount.sub(balanceInLock);
// We only lock up to the available CVX
uint256 maxCVX = IERC20Upgradeable(want).balanceOf(address(this));
if (cvxToLock > maxCVX) {
// Just lock what we can
LOCKER.lock(address(this), maxCVX, getBoostPayment());
} else {
// Lock proper
LOCKER.lock(address(this), cvxToLock, getBoostPayment());
}
// If anything left, send to vault
uint256 cvxLeft = IERC20Upgradeable(want).balanceOf(address(this));
if(cvxLeft > 0){
_transferToVault(cvxLeft);
}
}
} | Send rest of earned to tree We send all rest to avoid dust and avoid protecting the token We take difference of vault token to emit the event in shares rather than underlying | uint256 cvxCRVInitialBalance = CVXCRV_VAULT.balanceOf(BADGER_TREE);
| 7,665,361 | [
1,
3826,
3127,
434,
425,
1303,
329,
358,
2151,
1660,
1366,
777,
3127,
358,
4543,
302,
641,
471,
4543,
17151,
310,
326,
1147,
1660,
4862,
7114,
434,
9229,
1147,
358,
3626,
326,
871,
316,
24123,
9178,
2353,
6808,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2254,
5034,
8951,
92,
5093,
58,
4435,
13937,
273,
385,
58,
60,
5093,
58,
67,
27722,
2274,
18,
12296,
951,
12,
16234,
3101,
67,
26557,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.4.15;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant 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 constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Controlled {
/// @notice The address of the controller is the only address that can call
/// a function with this modifier
modifier onlyController { require(msg.sender == controller); _; }
address public controller;
function Controlled() public { controller = msg.sender;}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) public onlyController {
controller = _newController;
}
}
/*
Copyright 2016, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title MiniMeToken Contract
/// @author Jordi Baylina
/// @dev This token contract's goal is to make it easy for anyone to clone this
/// token using the token distribution at a given block, this will allow DAO's
/// and DApps to upgrade their features in a decentralized manner without
/// affecting the original token
/// @dev It is ERC20 compliant, but still needs to under go further testing.
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public;
}
/// @dev The actual token contract, the default controller is the msg.sender
/// that deploys the contract, so usually this token will be deployed by a
/// token controller contract, which Giveth will call a "Campaign"
contract MiniMeToken is Controlled {
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
string public version = 'MMT_0.2'; //An arbitrary versioning scheme
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
MiniMeToken public parentToken;
// `parentSnapShotBlock` is the block number from the Parent Token that was
// used to determine the initial distribution of the Clone Token
uint public parentSnapShotBlock;
// `creationBlock` is the block number that the Clone Token was created
uint public creationBlock;
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
// The factory used to create new clone tokens
MiniMeTokenFactory public tokenFactory;
////////////////
// Constructor
////////////////
/// @notice Constructor to create a MiniMeToken
/// @param _tokenFactory The address of the MiniMeTokenFactory contract that
/// will create the Clone token contracts, the token factory needs to be
/// deployed first
/// @param _parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param _parentSnapShotBlock Block of the parent token that will
/// determine the initial distribution of the clone token, set to 0 if it
/// is a new token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
function MiniMeToken(
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public {
tokenFactory = MiniMeTokenFactory(_tokenFactory);
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = MiniMeToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
return doTransfer(msg.sender, _to, _amount);
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount
) public returns (bool success) {
// The controller of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// controller of this contract, which in most situations should be
// another open source smart contract or 0x0
if (msg.sender != controller) {
require(transfersEnabled);
// The standard ERC 20 transferFrom functionality
if (allowed[_from][msg.sender] < _amount) return false;
allowed[_from][msg.sender] -= _amount;
}
return doTransfer(_from, _to, _amount);
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(address _from, address _to, uint _amount
) internal returns(bool) {
if (_amount == 0) {
return true;
}
require(parentSnapShotBlock < block.number);
// Do not allow transfer to 0x0 or the token contract itself
require((_to != 0) && (_to != address(this)));
// If the amount being transfered is more than the balance of the
// account the transfer returns false
var previousBalanceFrom = balanceOfAt(_from, block.number);
if (previousBalanceFrom < _amount) {
return false;
}
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
var previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
// An event to make the transfer easy to find on the blockchain
Transfer(_from, _to, _amount);
return true;
}
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender
) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(address _spender, uint256 _amount, bytes _extraData
) public returns (bool success) {
require(approve(_spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply() public constant returns (uint) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint _blockNumber) public constant
returns (uint) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0)
|| (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber`
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0)
|| (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Clone Token Method
////////////////
/// @notice Creates a new clone token with the initial distribution being
/// this token at `_snapshotBlock`
/// @param _cloneTokenName Name of the clone token
/// @param _cloneDecimalUnits Number of decimals of the smallest unit
/// @param _cloneTokenSymbol Symbol of the clone token
/// @param _snapshotBlock Block when the distribution of the parent token is
/// copied to set the initial distribution of the new clone token;
/// if the block is zero than the actual block, the current block is used
/// @param _transfersEnabled True if transfers are allowed in the clone
/// @return The address of the new MiniMeToken Contract
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) public returns(address) {
if (_snapshotBlock == 0) _snapshotBlock = block.number;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
_snapshotBlock,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
// An event to make the token easy to find on the blockchain
NewCloneToken(address(cloneToken), _snapshotBlock);
return address(cloneToken);
}
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount
) public onlyController returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
Transfer(0, _owner, _amount);
return true;
}
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _owner, uint _amount
) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
Transfer(_owner, 0, _amount);
return true;
}
////////////////
// Enable tokens transfers
////////////////
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) public onlyController {
transfersEnabled = _transfersEnabled;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint _block
) constant internal returns (uint) {
if (checkpoints.length == 0) return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value
) internal {
if ((checkpoints.length == 0)
|| (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
/// @dev Helper function to return a min betwen the two uints
/// PURE function
function min(uint a, uint b) internal constant returns (uint) {
return a < b ? a : b;
}
/// @notice The fallback function: If the contract's controller has not been
/// set to 0, then the `proxyPayment` method is called which relays the
/// ether and creates tokens as described in the token controller contract
function () public payable {
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) public onlyController {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
////////////////
// MiniMeTokenFactory
////////////////
/// @dev This contract is used to generate clone contracts from a contract.
/// In solidity this is the way to create a contract from a contract of the
/// same class
contract MiniMeTokenFactory {
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the controller of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
address _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken) {
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
contract StakeTreeWithTokenization {
using SafeMath for uint256;
uint public version = 2;
struct Funder {
bool exists;
uint balance;
uint withdrawalEntry;
uint contribution;
uint contributionClaimed;
}
mapping(address => Funder) public funders;
bool public live = true; // For sunsetting contract
uint public totalCurrentFunders = 0; // Keeps track of total funders
uint public withdrawalCounter = 0; // Keeps track of how many withdrawals have taken place
uint public sunsetWithdrawDate;
MiniMeToken public tokenContract;
MiniMeTokenFactory public tokenFactory;
bool public tokenized = false;
bool public canClaimTokens = false;
address public beneficiary; // Address for beneficiary
uint public sunsetWithdrawalPeriod; // How long it takes for beneficiary to swipe contract when put into sunset mode
uint public withdrawalPeriod; // How long the beneficiary has to wait withdraw
uint public minimumFundingAmount; // Setting used for setting minimum amounts to fund contract with
uint public lastWithdrawal; // Last withdrawal time
uint public nextWithdrawal; // Next withdrawal time
uint public contractStartTime; // For accounting purposes
event Payment(address indexed funder, uint amount);
event Refund(address indexed funder, uint amount);
event Withdrawal(uint amount);
event TokensClaimed(address indexed funder, uint amount);
event Sunset(bool hasSunset);
function StakeTreeWithTokenization(
address beneficiaryAddress,
uint withdrawalPeriodInit,
uint withdrawalStart,
uint sunsetWithdrawPeriodInit,
uint minimumFundingAmountInit) {
beneficiary = beneficiaryAddress;
withdrawalPeriod = withdrawalPeriodInit;
sunsetWithdrawalPeriod = sunsetWithdrawPeriodInit;
lastWithdrawal = withdrawalStart;
nextWithdrawal = lastWithdrawal + withdrawalPeriod;
minimumFundingAmount = minimumFundingAmountInit;
contractStartTime = now;
}
// Modifiers
modifier onlyByBeneficiary() {
require(msg.sender == beneficiary);
_;
}
modifier onlyWhenTokenized() {
require(isTokenized());
_;
}
modifier onlyByFunder() {
require(isFunder(msg.sender));
_;
}
modifier onlyAfterNextWithdrawalDate() {
require(now >= nextWithdrawal);
_;
}
modifier onlyWhenLive() {
require(live);
_;
}
modifier onlyWhenSunset() {
require(!live);
_;
}
/*
* External accounts can pay directly to contract to fund it.
*/
function () payable {
fund();
}
/*
* Additional api for contracts to use as well
* Can only happen when live and over a minimum amount set by the beneficiary
*/
function fund() public payable onlyWhenLive {
require(msg.value >= minimumFundingAmount);
// Only increase total funders when we have a new funder
if(!isFunder(msg.sender)) {
totalCurrentFunders = totalCurrentFunders.add(1); // Increase total funder count
funders[msg.sender] = Funder({
exists: true,
balance: msg.value,
withdrawalEntry: withdrawalCounter, // Set the withdrawal counter. Ie at which withdrawal the funder "entered" the patronage contract
contribution: 0,
contributionClaimed: 0
});
}
else {
consolidateFunder(msg.sender, msg.value);
}
Payment(msg.sender, msg.value);
}
// Pure functions
/*
* This function calculates how much the beneficiary can withdraw.
* Due to no floating points in Solidity, we will lose some fidelity
* if there's wei on the last digit. The beneficiary loses a neglibible amount
* to withdraw but this benefits the beneficiary again on later withdrawals.
* We multiply by 10 (which corresponds to the 10%)
* then divide by 100 to get the actual part.
*/
function calculateWithdrawalAmount(uint startAmount) public returns (uint){
return startAmount.mul(10).div(100); // 10%
}
/*
* This function calculates the refund amount for the funder.
* Due to no floating points in Solidity, we will lose some fidelity.
* The funder loses a neglibible amount to refund.
* The left over wei gets pooled to the fund.
*/
function calculateRefundAmount(uint amount, uint withdrawalTimes) public returns (uint) {
for(uint i=0; i<withdrawalTimes; i++){
amount = amount.mul(9).div(10);
}
return amount;
}
// Getter functions
/*
* To calculate the refund amount we look at how many times the beneficiary
* has withdrawn since the funder added their funds.
* We use that deduct 10% for each withdrawal.
*/
function getRefundAmountForFunder(address addr) public constant returns (uint) {
// Only calculate on-the-fly if funder has not been updated
if(shouldUpdateFunder(addr)) {
uint amount = funders[addr].balance;
uint withdrawalTimes = getHowManyWithdrawalsForFunder(addr);
return calculateRefundAmount(amount, withdrawalTimes);
}
else {
return funders[addr].balance;
}
}
function getFunderContribution(address funder) public constant returns (uint) {
// Only calculate on-the-fly if funder has not been updated
if(shouldUpdateFunder(funder)) {
uint oldBalance = funders[funder].balance;
uint newBalance = getRefundAmountForFunder(funder);
uint contribution = oldBalance.sub(newBalance);
return funders[funder].contribution.add(contribution);
}
else {
return funders[funder].contribution;
}
}
function getBeneficiary() public constant returns (address) {
return beneficiary;
}
function getCurrentTotalFunders() public constant returns (uint) {
return totalCurrentFunders;
}
function getWithdrawalCounter() public constant returns (uint) {
return withdrawalCounter;
}
function getWithdrawalEntryForFunder(address addr) public constant returns (uint) {
return funders[addr].withdrawalEntry;
}
function getContractBalance() public constant returns (uint256 balance) {
balance = this.balance;
}
function getFunderBalance(address funder) public constant returns (uint256) {
return getRefundAmountForFunder(funder);
}
function getFunderContributionClaimed(address addr) public constant returns (uint) {
return funders[addr].contributionClaimed;
}
function isFunder(address addr) public constant returns (bool) {
return funders[addr].exists;
}
function isTokenized() public constant returns (bool) {
return tokenized;
}
function shouldUpdateFunder(address funder) public constant returns (bool) {
return getWithdrawalEntryForFunder(funder) < withdrawalCounter;
}
function getHowManyWithdrawalsForFunder(address addr) private constant returns (uint) {
return withdrawalCounter.sub(getWithdrawalEntryForFunder(addr));
}
// State changing functions
function setMinimumFundingAmount(uint amount) external onlyByBeneficiary {
require(amount > 0);
minimumFundingAmount = amount;
}
function withdraw() external onlyByBeneficiary onlyAfterNextWithdrawalDate onlyWhenLive {
// Check
uint amount = calculateWithdrawalAmount(this.balance);
// Effects
withdrawalCounter = withdrawalCounter.add(1);
lastWithdrawal = now; // For tracking purposes
nextWithdrawal = nextWithdrawal + withdrawalPeriod; // Fixed period increase
// Interaction
beneficiary.transfer(amount);
Withdrawal(amount);
}
// Refunding by funder
// Only funders can refund their own funding
// Can only be sent back to the same address it was funded with
// We also remove the funder if they succesfully exit with their funds
function refund() external onlyByFunder {
// Check
uint walletBalance = this.balance;
uint amount = getRefundAmountForFunder(msg.sender);
require(amount > 0);
// Effects
removeFunder();
// Interaction
msg.sender.transfer(amount);
Refund(msg.sender, amount);
// Make sure this worked as intended
assert(this.balance == walletBalance-amount);
}
// Used when the funder wants to remove themselves as a funder
// without refunding. Their eth stays in the pool
function removeFunder() public onlyByFunder {
delete funders[msg.sender];
totalCurrentFunders = totalCurrentFunders.sub(1);
}
/*
* This is a bookkeeping function which updates the state for the funder
* when top up their funds.
*/
function consolidateFunder(address funder, uint newPayment) private {
// Update contribution
funders[funder].contribution = getFunderContribution(funder);
// Update balance
funders[funder].balance = getRefundAmountForFunder(funder).add(newPayment);
// Update withdrawal entry
funders[funder].withdrawalEntry = withdrawalCounter;
}
function addTokenization(string tokenName, string tokenSymbol, uint8 tokenDecimals ) external onlyByBeneficiary {
require(!isTokenized());
tokenFactory = new MiniMeTokenFactory();
tokenContract = tokenFactory.createCloneToken(0x0, 0, tokenName, tokenDecimals, tokenSymbol, true);
tokenized = true;
canClaimTokens = true;
}
function claimTokens() external onlyByFunder onlyWhenTokenized {
require(canClaimTokens);
uint contributionAmount = getFunderContribution(msg.sender);
uint contributionClaimedAmount = getFunderContributionClaimed(msg.sender);
// Only claim tokens if they have some left to claim
uint claimAmount = contributionAmount.sub(contributionClaimedAmount);
require(claimAmount > 0);
// Claim tokens
funders[msg.sender].contributionClaimed = contributionAmount;
tokenContract.generateTokens(msg.sender, claimAmount);
TokensClaimed(msg.sender, claimAmount);
}
/*
* The beneficiary can stop/enable funders from claiming more tokens.
* This opens up opportunities for tokenizing only happening for a set periods.
*/
function enableTokenClaiming(bool _enabled) external onlyWhenTokenized onlyByBeneficiary {
canClaimTokens = _enabled;
}
/* --- Sunsetting --- */
/*
* The beneficiary can decide to stop using this contract.
* They use this sunset function to put it into sunset mode.
* The beneficiary can then swipe rest of the funds after a set time
* if funders have not withdrawn their funds.
*/
function sunset() external onlyByBeneficiary onlyWhenLive {
sunsetWithdrawDate = now.add(sunsetWithdrawalPeriod);
live = false;
Sunset(true);
}
function swipe(address recipient) external onlyWhenSunset onlyByBeneficiary {
require(now >= sunsetWithdrawDate);
recipient.transfer(this.balance);
}
/* --- Token Contract Forwarding Controller Functions --- */
/*
* Allows beneficiary to call two additional functions on the token contract:
* claimTokens
* enabledTransfers
*
*/
function tokenContractClaimTokens(address _token) onlyByBeneficiary onlyWhenTokenized {
tokenContract.claimTokens(_token);
}
function tokenContractEnableTransfers(bool _transfersEnabled) onlyByBeneficiary onlyWhenTokenized {
tokenContract.enableTransfers(_transfersEnabled);
}
} | This function calculates how much the beneficiary can withdraw. Due to no floating points in Solidity, we will lose some fidelity if there's wei on the last digit. The beneficiary loses a neglibible amount to withdraw but this benefits the beneficiary again on later withdrawals. We multiply by 10 (which corresponds to the 10%) then divide by 100 to get the actual part./ | function calculateWithdrawalAmount(uint startAmount) public returns (uint){
}
| 7,211,564 | [
1,
2503,
445,
17264,
3661,
9816,
326,
27641,
74,
14463,
814,
848,
598,
9446,
18,
463,
344,
358,
1158,
13861,
3143,
316,
348,
7953,
560,
16,
732,
903,
29612,
2690,
13444,
292,
560,
309,
1915,
1807,
732,
77,
603,
326,
1142,
8035,
18,
1021,
27641,
74,
14463,
814,
437,
2420,
279,
4251,
2941,
1523,
3844,
358,
598,
9446,
1496,
333,
27641,
18352,
326,
27641,
74,
14463,
814,
3382,
603,
5137,
598,
9446,
1031,
18,
1660,
10194,
635,
1728,
261,
12784,
13955,
358,
326,
1728,
9,
13,
1508,
12326,
635,
2130,
358,
336,
326,
3214,
1087,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
4604,
1190,
9446,
287,
6275,
12,
11890,
787,
6275,
13,
1071,
1135,
261,
11890,
15329,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/43113/0x654B9A15C586f1250a02aDDEfc84216829Ecb962/sources/BondDepository.sol | token given as payment for bond
| address public immutable Fork; | 7,170,606 | [
1,
2316,
864,
487,
5184,
364,
8427,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
1758,
1071,
11732,
27599,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/4/0xBc9975EbC34617b5B82Cf7Aa9D5b199C2120cD85/sources/contracts/5_JokerCharlie.sol | _withdrawAddress = (ownerAddr == address(0)) ? msg.sender : ownerAddr; _proxyRegistryAddress = proxyAddr; _presaleWhiteList(); | ERC721("JokerCharlieTest", "JOKERST") {
_withdrawAddress = msg.sender;
_royaltyAddress = _withdrawAddress;
emit SaleStatus(isSaleActive);
emit PresaleStatus(isPresaleActive);
}
| 661,449 | [
1,
67,
1918,
9446,
1887,
273,
261,
8443,
3178,
422,
1758,
12,
20,
3719,
692,
1234,
18,
15330,
294,
3410,
3178,
31,
389,
5656,
4243,
1887,
273,
2889,
3178,
31,
389,
12202,
5349,
13407,
682,
5621,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1377,
4232,
39,
27,
5340,
2932,
46,
601,
264,
2156,
549,
73,
4709,
3113,
315,
46,
3141,
654,
882,
7923,
288,
203,
3639,
389,
1918,
9446,
1887,
273,
1234,
18,
15330,
31,
203,
3639,
389,
3800,
15006,
1887,
225,
273,
389,
1918,
9446,
1887,
31,
203,
3639,
3626,
348,
5349,
1482,
12,
291,
30746,
3896,
1769,
203,
3639,
3626,
18346,
5349,
1482,
12,
291,
12236,
5349,
3896,
1769,
540,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/3/0x777Ad6549e2a1fd15142cF1794e02Baa161be659/sources/home/jonathancole/Documents/GitHub/cryptokitties-clone/contracts/KittyMarketplace.sol | adds 1 to the activeOffers tracker. | activeOffers++;
| 8,228,743 | [
1,
25428,
404,
358,
326,
2695,
7210,
414,
9745,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2695,
7210,
414,
9904,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xd4bDCCa1CA76ceD6FC8BB1bA91C5D7c0Ca4fE567/sources/Comptroller.sol | Get max borrow or redeem considering cToken liquidity | uint cTokenLiquidity = cTokenModify.getCash();
| 3,684,642 | [
1,
967,
943,
29759,
578,
283,
24903,
24453,
276,
1345,
4501,
372,
24237,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2254,
276,
1345,
48,
18988,
24237,
273,
276,
1345,
11047,
18,
588,
39,
961,
5621,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x8c14692589190D08E917e38bBee3aC10eaf0acb4/sources/apexONE.sol | @dev Preventing unstable dumping and limit ambassador mine | modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
| 3,673,410 | [
1,
25828,
310,
640,
15021,
4569,
1382,
471,
1800,
13232,
428,
23671,
312,
558,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
9606,
30959,
41,
20279,
2888,
5349,
288,
203,
3639,
309,
261,
2867,
12,
2211,
2934,
12296,
225,
300,
3576,
18,
1132,
411,
600,
5349,
13937,
3039,
15329,
203,
1850,
2583,
12,
3576,
18,
1132,
1648,
943,
41,
20279,
510,
911,
1769,
203,
3639,
289,
203,
3639,
309,
261,
323,
1724,
1380,
67,
422,
374,
15329,
203,
1850,
2583,
12,
2536,
428,
361,
1383,
67,
63,
3576,
18,
15330,
65,
597,
1234,
18,
1132,
422,
374,
18,
2947,
225,
2437,
1769,
203,
3639,
289,
12107,
203,
3639,
309,
261,
323,
1724,
1380,
67,
411,
1666,
15329,
203,
1850,
2583,
12,
2536,
428,
361,
1383,
67,
63,
3576,
18,
15330,
65,
597,
1234,
18,
1132,
422,
374,
18,
5877,
225,
2437,
1769,
203,
3639,
289,
12107,
203,
3639,
309,
261,
323,
1724,
1380,
67,
422,
1666,
747,
443,
1724,
1380,
67,
631,
27,
15329,
203,
1850,
2583,
12,
2536,
428,
361,
1383,
67,
63,
3576,
18,
15330,
65,
597,
1234,
18,
1132,
422,
404,
225,
2437,
1769,
203,
3639,
289,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.